问:
How to pick a contact in Android Studio with AppCompatActivity?
```<code>Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
</code>```

This basic intent works when I extend Activity (i.e. "MainActivity extends Activity"), but not when I extend AppCompatActivity. Can someone explain why, please :| I've been trying to figure it out for days.

I just really want to keep the action bar I already have in an existing app while being able to let the user pick a contact.

Logcat spouted a lot of stuff, not sure how much to copy&paste but here's a log when I clicked the button with a try/catch block:

```<code>11-17 18:37:36.386 2790-2790/com.danie.contactstesting1 W/System.err: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
11-17 18:37:36.389 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:717)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at com.danie.contactstesting1.MainActivity$1.onClick(MainActivity.java:31)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View.performClick(View.java:6294)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View$PerformClick.run(View.java:24770)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:790)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Looper.loop(Looper.java:164)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
11-17 18:37:36.392 1378-3101/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 489826 , only wrote 489600
11-17 18:37:37.668 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
11-17 18:37:37.669 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
11-17 18:37:37.672 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
11-17 18:37:37.685 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - task received
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - TaskExecutor already running
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - retry #2 for com.android.voicemail.impl.ActivationTask@66adaa2 queued, executing in 5000
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask@66adaa2 added
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - minimal wait time:4999
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - sleep for 4999 millis
11-17 18:37:39.618 1378-1528/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 797294 , only wrote 644400
11-17 18:37:42.695 2064-3590/com.google.android.dialer I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask@66adaa2
11-17 18:37:42.697 2064-3590/com.google.android.dialer I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, [e2f7d48dd2b5ca523e7313cf4ba0f6ea830b6281], UserHandle{0} already migrated
11-17 18:37:42.740 2064-3590/com.google.android.dialer I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
11-17 18:37:42.741 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
11-17 18:37:42.763 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings - using TelephonyManager
11-17 18:37:42.767 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.sendVisualVoicemailSms - using TelephonyManager
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Do partial code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: After code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Increasing code cache capacity to 512KB
11-17 18:38:00.026 1388-1413/? D/hwcomposer: hw_composer sent 18 syncs in 60s
11-17 18:38:08.586 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.587 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.609 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.609 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.621 1585-1599/system_process E/memtrack: Couldn't load memtrack module
</code>```

Uhh okay embarrassing, I just had to use a lower request code (RESULT_PICK_CONTACT was 85500). Thanks CommonsWare for pointing me towards Logcat. Haha... Thanks everyone for quick responses as well!

答: I had to use a lower request code (RESULT_PICK_CONTACT was 85500). Thanks CommonsWare for pointing me towards Logcat (yes, I am 100% noob).</p>

Body:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

This basic intent works when I extend Activity (i.e. "MainActivity extends Activity"), but not when I extend AppCompatActivity. Can someone explain why, please :| I've been trying to figure it out for days.

I just really want to keep the action bar I already have in an existing app while being able to let the user pick a contact.

Logcat spouted a lot of stuff, not sure how much to copy&paste but here's a log when I clicked the button with a try/catch block:

11-17 18:37:36.386 2790-2790/com.danie.contactstesting1 W/System.err: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
11-17 18:37:36.389 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:717)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at com.danie.contactstesting1.MainActivity$1.onClick(MainActivity.java:31)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View.performClick(View.java:6294)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View$PerformClick.run(View.java:24770)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:790)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Looper.loop(Looper.java:164)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
11-17 18:37:36.392 1378-3101/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 489826 , only wrote 489600
11-17 18:37:37.668 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
11-17 18:37:37.669 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
11-17 18:37:37.672 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
11-17 18:37:37.685 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - task received
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - TaskExecutor already running
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - retry #2 for com.android.voicemail.impl.ActivationTask@66adaa2 queued, executing in 5000
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask@66adaa2 added
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - minimal wait time:4999
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - sleep for 4999 millis
11-17 18:37:39.618 1378-1528/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 797294 , only wrote 644400
11-17 18:37:42.695 2064-3590/com.google.android.dialer I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask@66adaa2
11-17 18:37:42.697 2064-3590/com.google.android.dialer I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, [e2f7d48dd2b5ca523e7313cf4ba0f6ea830b6281], UserHandle{0} already migrated
11-17 18:37:42.740 2064-3590/com.google.android.dialer I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
11-17 18:37:42.741 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
11-17 18:37:42.763 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings - using TelephonyManager
11-17 18:37:42.767 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.sendVisualVoicemailSms - using TelephonyManager
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Do partial code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: After code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Increasing code cache capacity to 512KB
11-17 18:38:00.026 1388-1413/? D/hwcomposer: hw_composer sent 18 syncs in 60s
11-17 18:38:08.586 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.587 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.609 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.609 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.621 1585-1599/system_process E/memtrack: Couldn't load memtrack module

Uhh okay embarrassing, I just had to use a lower request code (RESULT_PICK_CONTACT was 85500). Thanks CommonsWare for pointing me towards Logcat. Haha... Thanks everyone for quick responses as well!


来源: stackexchange

问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
There's no built-in function that handles character sets, but you simply use the substr_count function in a loop as such:</p>

```<code><?php
    $sourceCharacters = str_split('AGUXYZ');
    $targetString = 'Agriculture ID XYZ-A';
    $occurrenceCount = array();

    foreach($sourceCharacters as $currentCharacter) {
        $occurrenceCount[$currentCharacter] = substr_count($targetString, $currentCharacter);
    }

    print_r($occurrenceCount);
?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
There's no built-in function that handles character sets, but you simply use the substr_count function in a loop as such:

<?php
    $sourceCharacters = str_split('AGUXYZ');
    $targetString = 'Agriculture ID XYZ-A';
    $occurrenceCount = array();

    foreach($sourceCharacters as $currentCharacter) {
        $occurrenceCount[$currentCharacter] = substr_count($targetString, $currentCharacter);
    }

    print_r($occurrenceCount);
?>


问:
iPython macros operations
I am an engineer and I use a python REPL as an advanced calculator while working. I use the "previous output" feature of the REPL, which is _, often.

```<code>>>>45*0.344
15.48
>>>_*2
30.96
</code>```

Something like that.

For some reason I find it kind of a chore to type the underscore though. I've used the Haskell REPL, which uses "it" as the previous output variable, which I find easier to type.

I learned that iPython lets you define macros that execute some code. So I popped open an iPython shell and defined a %macro called "it" that mimics the "_".

```<code>In [1]: _
Out[1]: ''

In [2]: %macro it 1
Macro `it` created. To execute, type its name (without quotes).
=== Macro contents: ===
_
</code>```

I can call "it" like so:

```<code>In [1]: 4
Out[1]: 4

In [2]: it
Out[2]: 4
</code>```

However, when I try to do something with "it" like it*4, I get the error unsupported operand type(s) for *: 'Macro' and 'int'.

I want "it" to be the type it's returning instead of the type Macro, so that I can use it just like I use "_".

答:
Instead of going the macro route you could also change the code where _ gets assigned. sys.displayhook does this and can be changed:

The display of these values can be customized by assigning another
  one-argument function to sys.displayhook.

So we can simply save in __builtins__.it or whatever name you like:

```<code>import sys
ipython_displayhook = sys.displayhook
def mydisplayhook(value):
    if value is not None:
        __builtins__.it = value
    return ipython_displayhook(value)
sys.displayhook = mydisplayhook
</code>```

This works in the normal python shell, but somehow ipython prevents with tampering with sys.displayhook. The code in ipython that handles the displayhook is in IPython.core.displayhook.DisplayHook so we can monkey patch that:

```<code>import IPython.core.displayhook
__call__ = IPython.core.displayhook.DisplayHook.__call__

def mycall(self, value):
    if value is not None:
        __builtins__.it = value
    __call__(self, value)

IPython.core.displayhook.DisplayHook.__call__ = mycall
</code>```

This is a bit hacky. Things may break, but after testing this for 5 seconds it seems that it works.

You probably don't want to type that everytime you start ipython, but we can automate that. This answer says you can simply put a file into ~/.ipython/profile_default/startup/ which gets then executed everytime.

ContentLicense: CC BY-SA 3.0

Title: iPython macros operations

Body:
I am an engineer and I use a python REPL as an advanced calculator while working. I use the "previous output" feature of the REPL, which is _, often.

>>>45*0.344
15.48
>>>_*2
30.96

Something like that.

For some reason I find it kind of a chore to type the underscore though. I've used the Haskell REPL, which uses "it" as the previous output variable, which I find easier to type.

I learned that iPython lets you define macros that execute some code. So I popped open an iPython shell and defined a %macro called "it" that mimics the "_".

In [1]: _
Out[1]: ''

In [2]: %macro it 1
Macro `it` created. To execute, type its name (without quotes).
=== Macro contents: ===
_

I can call "it" like so:

In [1]: 4
Out[1]: 4

In [2]: it
Out[2]: 4

However, when I try to do something with "it" like it*4, I get the error unsupported operand type(s) for *: 'Macro' and 'int'.

I want "it" to be the type it's returning instead of the type Macro, so that I can use it just like I use "_".

Body:
Instead of going the macro route you could also change the code where _ gets assigned. sys.displayhook does this and can be changed:

The display of these values can be customized by assigning another
  one-argument function to sys.displayhook.

So we can simply save in __builtins__.it or whatever name you like:

import sys
ipython_displayhook = sys.displayhook
def mydisplayhook(value):
    if value is not None:
        __builtins__.it = value
    return ipython_displayhook(value)
sys.displayhook = mydisplayhook

This works in the normal python shell, but somehow ipython prevents with tampering with sys.displayhook. The code in ipython that handles the displayhook is in IPython.core.displayhook.DisplayHook so we can monkey patch that:

import IPython.core.displayhook
__call__ = IPython.core.displayhook.DisplayHook.__call__

def mycall(self, value):
    if value is not None:
        __builtins__.it = value
    __call__(self, value)

IPython.core.displayhook.DisplayHook.__call__ = mycall

This is a bit hacky. Things may break, but after testing this for 5 seconds it seems that it works.

You probably don't want to type that everytime you start ipython, but we can automate that. This answer says you can simply put a file into ~/.ipython/profile_default/startup/ which gets then executed everytime.


问:
Get some random element from an Array on Iteration
Ok this is my first time with asking for help in this community and I'll try to be as specific as I can. Here is what I want to achieve.
I want to give a list of 4 keys from the array which need to be unique obviously. I will put the below in a for loop but am i on the right track below

Given an array of elements in the array...

```<code>var keysRand = new Array("E","F","G", "A", "B", "C", "D", "F#", "G#", "A#", "D#", "C#")
</code>```

I want to go through the array, pick a random key:

```<code>randno1 = keysRand[Math.floor( Math.random() * keysRand.length )];
</code>```

Get the index of the Key I choose

```<code>var a = keysRand.indexOf(randno1)
</code>```

Push it to top of list and get rid of it.

```<code>keysRand.push(keysRand.splice(a, 1)[0]);
keysRand1.pop();
</code>```

This seems to work most of the time but im seeing undefined entries sometimes when doing console.log().
Am I on the right track, or is there a better way to approach this?

答:
Your problem is that keysRand.splice(a, 1) actually removes the element by itself and there is no need to then move it and pop it.

For Example:

What you have here:

```<code>keysRand.push(keysRand.splice(a, 1)[0]);
keysRand1.pop();
</code>```

Should just be:

```<code>keysRand.splice(a, 1)
</code>```

Also

You already have the index with: Math.floor( Math.random() * keysRand.length ), so your whole code can be shortened to:

```<code>var keysRand = new Array("E","F","G", "A", "B", "C", "D", "F#", "G#", "A#", "D#", "C#");
var index = Math.floor( Math.random() * keysRand.length );
keysRand.splice(index, 1);
</code>```

Body:
Ok this is my first time with asking for help in this community and I'll try to be as specific as I can. Here is what I want to achieve.
I want to give a list of 4 keys from the array which need to be unique obviously. I will put the below in a for loop but am i on the right track below

Given an array of elements in the array...

var keysRand = new Array("E","F","G", "A", "B", "C", "D", "F#", "G#", "A#", "D#", "C#")

I want to go through the array, pick a random key:

randno1 = keysRand[Math.floor( Math.random() * keysRand.length )];

Get the index of the Key I choose

var a = keysRand.indexOf(randno1)

Push it to top of list and get rid of it.

keysRand.push(keysRand.splice(a, 1)[0]);
keysRand1.pop();

This seems to work most of the time but im seeing undefined entries sometimes when doing console.log().
Am I on the right track, or is there a better way to approach this?

Body:
Your problem is that keysRand.splice(a, 1) actually removes the element by itself and there is no need to then move it and pop it.

For Example:

What you have here:

keysRand.push(keysRand.splice(a, 1)[0]);
keysRand1.pop();

Should just be:

keysRand.splice(a, 1)

Also

You already have the index with: Math.floor( Math.random() * keysRand.length ), so your whole code can be shortened to:

var keysRand = new Array("E","F","G", "A", "B", "C", "D", "F#", "G#", "A#", "D#", "C#");
var index = Math.floor( Math.random() * keysRand.length );
keysRand.splice(index, 1);


问:
Is there a more elegant way to declare my javascript variables?
I'm writing a hangman game and it's working great, but this block of variables is really quite ugly. I know I've done something in PHP before where I've put all the variables I've needed into an array and pumped them out. Is there a way to accomplish this with Javascript while grabbing my DOM elements?</p>

```<code>let _ = [];
let correct = [];
let wrong = [];
let underscores = document.querySelector('.underscores');
let correctBlock = document.querySelector('.correct');
let wrongBlock = document.querySelector('.wrong');
let scoreBlock = document.querySelector('#score');
let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');
</code>```

答:
The shortest you'll be able to get is:

```<code>let _ = [],
  correct = [],
  wrong = [],
  underscores = document.querySelector('.underscores'),
  correctBlock = document.querySelector('.correct'),
  wrongBlock = document.querySelector('.wrong'),
  scoreBlock = document.querySelector('#score'),
  btn = document.querySelector('.btn'),
  hint = document.querySelector('.hint');
</code>```

I can't see a way to generalize/compress this, as the elements you are selecting are all different. Honestly, this is fine!

Body:
I'm writing a hangman game and it's working great, but this block of variables is really quite ugly. I know I've done something in PHP before where I've put all the variables I've needed into an array and pumped them out. Is there a way to accomplish this with Javascript while grabbing my DOM elements?

let _ = [];
let correct = [];
let wrong = [];
let underscores = document.querySelector('.underscores');
let correctBlock = document.querySelector('.correct');
let wrongBlock = document.querySelector('.wrong');
let scoreBlock = document.querySelector('#score');
let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');

Body:
The shortest you'll be able to get is:

let _ = [],
  correct = [],
  wrong = [],
  underscores = document.querySelector('.underscores'),
  correctBlock = document.querySelector('.correct'),
  wrongBlock = document.querySelector('.wrong'),
  scoreBlock = document.querySelector('#score'),
  btn = document.querySelector('.btn'),
  hint = document.querySelector('.hint');

I can't see a way to generalize/compress this, as the elements you are selecting are all different. Honestly, this is fine!


问:
What's the best way to work with SQL Server data non-programmatically?
We have a SQL server database. To manipulate the data non-programmatically, I can use SQL Server Management Studio by right-clicking a table and selecting "Open Table". However this is slow for very large tables and sorting and filtering is cumbersome.

Typically what we have done until now is to create an Access database containing linked tables which point to the SQL Server tables and views. Opening a large table is much faster this way, and Access has easy-to-use right-click filtering and sorting.

However, since Access 2007, sorting in particular has been quite slow when working with large tables. The Access database can also inadvertently lock the database tables, blocking other processes that may need to access the data. Creating the Access database in the first place, and updating it when new tables are added to SQL Server, is also tedious.

Is there a better way to work with the data that offers the usability of Access without its drawbacks?

答:
Joel Coehoorn's answer is of course correct, that if the data is critical or there are naive users using the data, then a application front end should be developed.  That being said, I have cases where a wise user (ok, me) user needs to just get in there and poke around.

Instead of directly looking at the tables, use MS Access but use queries to narrow down what you're looking at both column wise and row wise.  That will improve the speed.  Then edit the query properties and make sure that the query is No Locks.  That should eliminate any blocking behavior.  You may want to limit the number of rows returned which again will improve the speed.  You can still edit the data in the query as you look at it.

Depending on what you're looking at, it may also be useful to set up database Views in the SQL Server to do some of the heavy lifting on the server rather than on the client.

OwnerDisplayName: Phillip Wells

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Knox


问:
Geolocation feedback while accepting the request
the geolocation implementation is quite good and got few steps to observe but only on thing is missing, i guess.
Im not able to see if the user accepted the request or not ( before i get the position object ), i dunno if the user just ignores my request ( during my timeout ) or if the request just get lost ( and the failure callback doesnt get called for no reason ).

It would be useful to set a timestamp when the user accepts the request, i couldnt find anything which gives me that kind of response.

答:
It is part of the Geolocation API:

```<code>// navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
navigator.geolocation.getCurrentPosition(
  function(position){
    //do something with position;
  }, function(){
    //handle condition where position is not available
    //more specifically you can check the error code...
    //error.code == 1
    if(error.PERMISSION_DENIED){
      alert("you denied me! ");
    }
});
</code>```

If you specify the errorCallback... then you can track if the user has declined to provide access.

Possible error codes include:

```<code>error.PERMISSION_DENIED    (numeric value 1)
error.POSITION_UNAVAILABLE (numeric value 2)
error.TIMEOUT              (numeric value 3)
</code>```

Body:
It is part of the Geolocation API:

// navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
navigator.geolocation.getCurrentPosition(
  function(position){
    //do something with position;
  }, function(){
    //handle condition where position is not available
    //more specifically you can check the error code...
    //error.code == 1
    if(error.PERMISSION_DENIED){
      alert("you denied me! ");
    }
});

If you specify the errorCallback... then you can track if the user has declined to provide access.

Possible error codes include:

error.PERMISSION_DENIED    (numeric value 1)
error.POSITION_UNAVAILABLE (numeric value 2)
error.TIMEOUT              (numeric value 3)


问:
Django - loop over list in template to check if a value exists, display something later
I find a list of Upvote model instances attached to a specific question, so I can check if the current user has already upvoted the question.  I want to display a different button if the user has already upvoted this particular question.  The problem is, the current {% if .. %} tags don't work, because a question can have many upvotes.  I only need the {% if ..%} tags to simply check to see if one of the upvote.user == request.user.

How do I approach this situation?  I'm looking at different solutions, like creating a variable and setting that to True if a match was found (seems difficult), or writing a custom template tag.  I feel like I'm over-complicating this issue though.

HTML Template

```<code>{% for question in questions %}
        {% for upvote in question.upvote_set.all %}
        {% if upvote.user == request.user %}
        # Display the upvote button
        {% else %}
        # Display a different button
        {% endif %}
        {% endfor %}
</code>```

models.py

```<code>class Question(models.Model):
    # ... code
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='question', null=True, blank=True)

class Upvote(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

答:
Django template boolean expressions support an in operator, but I don't think you can flatten the FK relationships enough to query it with just template syntax.

You could either:

a) Add a method to the Question model to return a list of upvoting users:

```<code>def upvoters(self):
    return self.upvote_set.all().values_list('user', flat=True)
</code>```

Then test this in the template:

```<code>{% if request.user in question.upvoters %}
</code>```

Or b) Annotate the question instances in the view:

```<code># assuming questions is a queryset, I think the for loop means this is redundant but I'm including it for clarity
questions = list(questions)
# then modify the model instances
for question in questions:
    question.is_upvoted = question.upvote_set.filter(user=request.user).exists()
</code>```

Then check {% if question.is_upvoted %} in your template.

Keep an eye on performance with either of these, these should be fine for reasonably small numbers of questions and upvoters but aren't particularly optimized. Annotation with a conditional expression is probably more efficient but outside of my direct experience.

Body:
I find a list of Upvote model instances attached to a specific question, so I can check if the current user has already upvoted the question.  I want to display a different button if the user has already upvoted this particular question.  The problem is, the current {% if .. %} tags don't work, because a question can have many upvotes.  I only need the {% if ..%} tags to simply check to see if one of the upvote.user == request.user.

How do I approach this situation?  I'm looking at different solutions, like creating a variable and setting that to True if a match was found (seems difficult), or writing a custom template tag.  I feel like I'm over-complicating this issue though.

HTML Template

{% for question in questions %}
        {% for upvote in question.upvote_set.all %}
        {% if upvote.user == request.user %}
        # Display the upvote button
        {% else %}
        # Display a different button
        {% endif %}
        {% endfor %}

models.py

class Question(models.Model):
    # ... code
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='question', null=True, blank=True)

class Upvote(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

Body:
Django template boolean expressions support an in operator, but I don't think you can flatten the FK relationships enough to query it with just template syntax.

You could either:

a) Add a method to the Question model to return a list of upvoting users:

def upvoters(self):
    return self.upvote_set.all().values_list('user', flat=True)

Then test this in the template:

{% if request.user in question.upvoters %}

Or b) Annotate the question instances in the view:

# assuming questions is a queryset, I think the for loop means this is redundant but I'm including it for clarity
questions = list(questions)
# then modify the model instances
for question in questions:
    question.is_upvoted = question.upvote_set.filter(user=request.user).exists()

Then check {% if question.is_upvoted %} in your template.

Keep an eye on performance with either of these, these should be fine for reasonably small numbers of questions and upvoters but aren't particularly optimized. Annotation with a conditional expression is probably more efficient but outside of my direct experience.


问:
Show Hide Text using JavaScript by words not characters
I have found this code that works great, but it counts by characters. As a result the words sometimes are incomplete, and when you click on read more it creates a space in the word. I have also found a function of how to count by words, but I don't have the know how to merge the two. Below is my working code, and the function
Thanks

====== Working Code ======

// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

                var contentExcert = content.substr(0, showChar);
                var contentRest = content.substr(showChar, content.length - showChar);
                var html = contentExcert + '' + ellipsestext + '  ' + contentRest + '' + moretext + '';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });```
</div>
</div>
</p>

<p>====== Function Code ======</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function limitWords(element, quantity){

   var text = $(element).text();

   var words = text.split(" ");

   quantity = Math.min( quantity, words.length );

   $(element).text( words.slice(0,quantity) + "..." );

}</code>```

答:
// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

    var charCount = 0;
    var contentExcert = content.split(" ").map((n)=>{
     charCount += n.length + 1;
     return charCount - 1 <= showChar ? n : false;
     }).filter(n=>n).join(" ");
     charCount = 0;
    var contentRest = content.split(" ").map((n)=>{
     charCount += n.length + 1;
     return charCount - 1 >= showChar ? n : false;
     }).filter(n=>n).join(" ");
                var html = contentExcert + '' + ellipsestext + '  ' + contentRest + '' + moretext + '';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });```

Body:
I have found this code that works great, but it counts by characters. As a result the words sometimes are incomplete, and when you click on read more it creates a space in the word. I have also found a function of how to count by words, but I don't have the know how to merge the two. Below is my working code, and the function
Thanks

====== Working Code ======

// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

                var contentExcert = content.substr(0, showChar);
                var contentRest = content.substr(showChar, content.length - showChar);
                var html = contentExcert + '' + ellipsestext + '  ' + contentRest + '' + moretext + '';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });

====== Function Code ======

function limitWords(element, quantity){

   var text = $(element).text();

   var words = text.split(" ");

   quantity = Math.min( quantity, words.length );

   $(element).text( words.slice(0,quantity) + "..." );

}

Body:
// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

    var charCount = 0;
    var contentExcert = content.split(" ").map((n)=>{
     charCount += n.length + 1;
     return charCount - 1 <= showChar ? n : false;
     }).filter(n=>n).join(" ");
     charCount = 0;
    var contentRest = content.split(" ").map((n)=>{
     charCount += n.length + 1;
     return charCount - 1 >= showChar ? n : false;
     }).filter(n=>n).join(" ");
                var html = contentExcert + '<span class="toggle-text-ellipses">' + ellipsestext + ' </span> <span class="toggle-text-content"><span>' + contentRest + '</span><a href="javascript:;" class="btn btn--primary btn--dark toggle-text-link">' + moretext + '</a></span>';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });


答:
Declare static variables e.g. functions, references to elements with const keyword (instead of let).
Instead of repeating let/const keyword, just use comma operators:

```<code>const underscores = document.querySelector('.underscores'),
      correctBlock = document.querySelector('.correct'),
      wrongBlock = document.querySelector('.wrong');
</code>```

etc.

Title: Is there a more elegant way to declare my javascript variables?

Body:
Declare static variables e.g. functions, references to elements with const keyword (instead of let).
Instead of repeating let/const keyword, just use comma operators:

const underscores = document.querySelector('.underscores'),
      correctBlock = document.querySelector('.correct'),
      wrongBlock = document.querySelector('.wrong');

etc.


问:
Set different label in dropdown vs selected value in AngularJS selector
A form has 2 fields, a selector and a (sometimes) non editable input field. When the user selects something in the selector both fields are filled. The selector shows a date-time and a related label goes to the non editable field. To make the selection more user friendly I need to display in the selector dropdown the data-time concatenated with the label to allow the user to chose the rigth option if two options have the same date but different label. The problem is that after the user chooses an option then the selected value in the selector should have just the date and not the label (this is just shown in its own field). I have added two images to make it clear.

This is the Session Group dropdown with the concatenated date-time and label:

When a value is selected the label should be removed from the display value, since it is shown in the Thermal Profile field:

The ng-options code of the selector looks like this:

```<code>ng-options="opt.id as ((opt.sessions_datetime | date:'short') + ' (' + (opt.thermal_profiles_label || '') + ')') for opt in selectors.sessions_groups"
</code>```

How can the label be added only when the dropdown is displayed, but not when the selector shows the selected value?

I have created a simplified Plunker here:

https://plnkr.co/edit/aDVOFuojDhFSV15BdPU0?p=preview

Note: AngularJS 1.5.0

答:
Ternary conditions are really helpful getting workaround for these kind of issues. To get a workaround for your requirement, I've used the same approach (ternary conditions). What is happening here is whenever a value is selected, you can save the id of that selected value and then make a decision on the base of that  id whether to hide or show the labels.

here is the full code.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.session = {
    sessions_groups_id: null,
    thermal_profiles_id: null
  }
  $scope.sessions_groups = [{
    id: 0,
    sessions_datetime: '2017-11-17',
    thermal_profiles_id: 0,
    thermal_profiles_label: 'Baseline'
  }, {
    id: 1,
    sessions_datetime: '2017-11-17',
    thermal_profiles_id: 1,
    thermal_profiles_label: '+24h'

  }];
  $scope.thermal_profiles = [{
    id: 0,
    label: 'Baseline'
  }, {
    id: 1,
    label: '+24h'
  }, {
    id: 2,
    label: '+36h'
  }];
  $scope.sessionsGroupsChange = function(thermal_profiles_id) {
     $scope.sessions_groups.map((e)=>{
     if(e.id == thermal_profiles_id)
      $scope.session.thermal_profiles_id = e.thermal_profiles_id
   });
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<!DOCTYPE html>
<html ng-cloak ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />

  </head>

  <body ng-controller="MainCtrl">

    <p><b>Sessions Groups selector</b>
    <br/>
    The dropdown displays the date concatenated with the thermal profile label
    <br/>
    But after selecting a value it should only display the date. The thermal profile label will be visible in the thermal profiles selector
    </p>
  <select id="sessions_groups_id"
    name="sessions_groups_id"
    ng-model="session.sessions_groups_id"
    ng-change="sessionsGroupsChange(session.sessions_groups_id)">
   <option ng-repeat="r in sessions_groups" value="{{r.id}}" >
     {{r.sessions_datetime }} {{session.sessions_groups_id == r.id ? '' : '(' + r.thermal_profiles_label +')'  }}
   </option>
   </select>

  <br/>

    <p><b>Thermal Profile selector</b>
    <br/>
    Displays the thermal profile label asociated with the value selected in the previuos selector.
    <br/>
    Here it is always disabled but in real app can be enabled under some conditions.
    </p>
  <select id="thermal_profiles_id"
   name="thermal_profiles_id"
   ng-model="session.thermal_profiles_id"
   ng-disabled="true"
   ng-options="opt.id as opt.label for opt in thermal_profiles">
   <option value></option>
  </select>
  </body>

</html></code>```

Ps. It's always confusing for me to use ng-options angular directive, that's why I prefer to use ng-repeat on <option>. This just makes things more easy to understand.

There was another problem of page/template loading in your application. Please have a look at ngCloak. I've used this app to smoothen up the template loading.
What ngCloak does is

The ngCloak directive is used to prevent the Angular html template
  from being briefly displayed by the browser in its raw (uncompiled)
  form while your application is loading. Use this directive to avoid
  the undesirable flicker effect caused by the html template display.

Hope this was helpful.

Body:
A form has 2 fields, a selector and a (sometimes) non editable input field. When the user selects something in the selector both fields are filled. The selector shows a date-time and a related label goes to the non editable field. To make the selection more user friendly I need to display in the selector dropdown the data-time concatenated with the label to allow the user to chose the rigth option if two options have the same date but different label. The problem is that after the user chooses an option then the selected value in the selector should have just the date and not the label (this is just shown in its own field). I have added two images to make it clear.

This is the Session Group dropdown with the concatenated date-time and label:

When a value is selected the label should be removed from the display value, since it is shown in the Thermal Profile field:

The ng-options code of the selector looks like this:

ng-options="opt.id as ((opt.sessions_datetime | date:'short') + ' (' + (opt.thermal_profiles_label || '') + ')') for opt in selectors.sessions_groups"

How can the label be added only when the dropdown is displayed, but not when the selector shows the selected value?

I have created a simplified Plunker here:

https://plnkr.co/edit/aDVOFuojDhFSV15BdPU0?p=preview

Note: AngularJS 1.5.0

Body:
Ternary conditions are really helpful getting workaround for these kind of issues. To get a workaround for your requirement, I've used the same approach (ternary conditions). What is happening here is whenever a value is selected, you can save the id of that selected value and then make a decision on the base of that  id whether to hide or show the labels.

here is the full code.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.session = {
    sessions_groups_id: null,
    thermal_profiles_id: null
  }
  $scope.sessions_groups = [{
    id: 0,
    sessions_datetime: '2017-11-17',
    thermal_profiles_id: 0,
    thermal_profiles_label: 'Baseline'
  }, {
    id: 1,
    sessions_datetime: '2017-11-17',
    thermal_profiles_id: 1,
    thermal_profiles_label: '+24h'

  }];
  $scope.thermal_profiles = [{
    id: 0,
    label: 'Baseline'
  }, {
    id: 1,
    label: '+24h'
  }, {
    id: 2,
    label: '+36h'
  }];
  $scope.sessionsGroupsChange = function(thermal_profiles_id) {
     $scope.sessions_groups.map((e)=>{
     if(e.id == thermal_profiles_id)
      $scope.session.thermal_profiles_id = e.thermal_profiles_id
   });
  }

});

<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<!DOCTYPE html>
<html ng-cloak ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />

  </head>

  <body ng-controller="MainCtrl">

    <p><b>Sessions Groups selector</b>
    <br/>
    The dropdown displays the date concatenated with the thermal profile label
    <br/>
    But after selecting a value it should only display the date. The thermal profile label will be visible in the thermal profiles selector
    </p>
  <select id="sessions_groups_id"
    name="sessions_groups_id"
    ng-model="session.sessions_groups_id"
    ng-change="sessionsGroupsChange(session.sessions_groups_id)">
   <option ng-repeat="r in sessions_groups" value="{{r.id}}" >
     {{r.sessions_datetime }} {{session.sessions_groups_id == r.id ? '' : '(' + r.thermal_profiles_label +')'  }}
   </option>
   </select>

  <br/>

    <p><b>Thermal Profile selector</b>
    <br/>
    Displays the thermal profile label asociated with the value selected in the previuos selector.
    <br/>
    Here it is always disabled but in real app can be enabled under some conditions.
    </p>
  <select id="thermal_profiles_id"
   name="thermal_profiles_id"
   ng-model="session.thermal_profiles_id"
   ng-disabled="true"
   ng-options="opt.id as opt.label for opt in thermal_profiles">
   <option value></option>
  </select>
  </body>

</html>

Ps. It's always confusing for me to use ng-options angular directive, that's why I prefer to use ng-repeat on <option>. This just makes things more easy to understand.

There was another problem of page/template loading in your application. Please have a look at ngCloak. I've used this app to smoothen up the template loading.
What ngCloak does is

The ngCloak directive is used to prevent the Angular html template
  from being briefly displayed by the browser in its raw (uncompiled)
  form while your application is loading. Use this directive to avoid
  the undesirable flicker effect caused by the html template display.

Hope this was helpful.


答:
I think you're referring to the double $ in PHP? (it's been a while)

No, sorry.

I suggest you create a map to keep things contained:

```<code>let score = {
  _: [],
  correct: [],
  wrong: []
}

let blocks = {
  underscores: document.querySelector('.underscores'),
  correct: document.querySelector('.correct'),
  wrong: document.querySelector('.wrong'),
  score: document.querySelector('#score')
}

let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');
</code>```

Usage:

```<code>score.wrong.push('...')
</code>```

Body:
I think you're referring to the double $ in PHP? (it's been a while)

No, sorry.

I suggest you create a map to keep things contained:

let score = {
  _: [],
  correct: [],
  wrong: []
}

let blocks = {
  underscores: document.querySelector('.underscores'),
  correct: document.querySelector('.correct'),
  wrong: document.querySelector('.wrong'),
  score: document.querySelector('#score')
}

let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');

Usage:

score.wrong.push('...')


问:
Default project id in BigQuery Java API
I am performing a query using the BigQuery Java API with the following code:

```<code>  try (FileInputStream input = new FileInputStream(serviceAccountKeyFile)) {

     GoogleCredentials credentials = GoogleCredentials.fromStream(input);

     BigQuery bigQuery = BigQueryOptions.newBuilder()
           .setCredentials(credentials)
           .build()
           .getService();

     QueryRequest request = QueryRequest.of("SELECT * FROM foo.Bar");
     QueryResponse response = bigQuery.query(request);

     // Handle the response ...

  }
</code>```

Notice that I am using a specific service account whose key file is given by serviceAccountKeyFile.

I was expecting that the API would pick up the project_id from the key file.  But it is actually picking up the project_id from the default key file referenced by the GOOGLE_APPLICATION_CREDENTIALS environment variable.

This seems like a bug to me.  Is there a way to workaround the bug by setting the default project explicitly?

答:
I don't believe the project is coming from GOOGLE_APPLICATION_CREDENTIALS. I suspect that the project being picked up is the gcloud default project set by gcloud init or gcloud config set project.

From my testing, BigQuery doesn't use a project where the service account is created. I think the key is used only for authorization, and you always have to set a target project. There are a number of ways:

.setProjectId(<target-project>) in the builder

Define GOOGLE_CLOUD_PROJECT

gcloud config set project <target-project>

The query job will then be created in target-project. Of course, your service key should have access to target-project, which may or may not be the same project where your key is created. That is, you can run a query on projects other than the project where your key is created, as long as your key has permission to do so.

Title: Default project id in BigQuery Java API

Body:
I am performing a query using the BigQuery Java API with the following code:

  try (FileInputStream input = new FileInputStream(serviceAccountKeyFile)) {

     GoogleCredentials credentials = GoogleCredentials.fromStream(input);

     BigQuery bigQuery = BigQueryOptions.newBuilder()
           .setCredentials(credentials)
           .build()
           .getService();

     QueryRequest request = QueryRequest.of("SELECT * FROM foo.Bar");
     QueryResponse response = bigQuery.query(request);

     // Handle the response ...

  }

Notice that I am using a specific service account whose key file is given by serviceAccountKeyFile.

I was expecting that the API would pick up the project_id from the key file.  But it is actually picking up the project_id from the default key file referenced by the GOOGLE_APPLICATION_CREDENTIALS environment variable.

This seems like a bug to me.  Is there a way to workaround the bug by setting the default project explicitly?


问:
How to generate homophones on substring level?
I want to generate homophones of words programmatically. Meaning, words that sound similar to the original words.

I've come across the Soundex algorithm, but it just replaces some characters with other characters (like t instead of d). Are there any lists or algorithms that are a little bit more sophisticated, providing at least homophone substrings?

Important: I want to apply this on words that aren't in dictionaries, meaning that I can't rely on whole, real words.

EDIT:

The input is a string which is often a proper name and therefore in no standard (homophone) dictionary. An example could be Google or McDonald's (just to name two popular named entities, but many are much more unpopular).

The output is then a (random) homophone of this string. Since words often have more than one homophone, a single (random) one is my goal. In the case of Google, a homophone could be gugel, or MacDonald's for McDonald's.

答:
How to do this well is a research topic. See for example http://www.inf.ufpr.br/didonet/articles/2014_FPSS.pdf.

But suppose that you want to roll your own.

The first step is figuring out how to turn the letters that you are given into a representation of what it sounds like.  This is a very hard problem with guessing required.  (eg What sound does "read" make?  Depends on whether you are going to read, or you already read!)  However text to phonemes converter suggests that Arabet has solved this for English.

Next you'll want this to have been done for every word in a dictionary.  Assuming that you can do that for one word, that's just a script.

Then you'll want it stored in a data structure where you can easily find similar sounds.  That is in principle no difference than the sort of algorithms that are used for autocorrect for spelling.  Only with phonemes instead of letters.  You can get a sense of how to do that with http://norvig.com/spell-correct.html.  Or try to implement something like what is described in http://fastss.csg.uzh.ch/ifi-2007.02.pdf.

And that is it.

ContentLicense: CC BY-SA 4.0


问:
Numpy: stack duplicates of matrix in new dimension
I have a 3x3 numpy array and I want to create a 3x3xC matrix where the new dimension consists of exact copies of the original 3x3 array. I am sure this is asked somewhere but I couldn't find the best way. I worked out how to do this for a simple 1 dimensional array x:

```<code>new_x = np.tile(np.array(x, (C, 1))
</code>```

which repeats the array, then do:

```<code>np.transpose(np.expand_dims(new_x, axis=2),(2,1,0))
</code>```

which expands the dimension and switches the axis so that the array is repeated in the 3rd dimension (although this works I'm not sure if this is the best way to do it either) - what is the most efficient way to do this for a general n x n numpy array?

Body:
I have a 3x3 numpy array and I want to create a 3x3xC matrix where the new dimension consists of exact copies of the original 3x3 array. I am sure this is asked somewhere but I couldn't find the best way. I worked out how to do this for a simple 1 dimensional array x:

new_x = np.tile(np.array(x, (C, 1))

which repeats the array, then do:

np.transpose(np.expand_dims(new_x, axis=2),(2,1,0))

which expands the dimension and switches the axis so that the array is repeated in the 3rd dimension (although this works I'm not sure if this is the best way to do it either) - what is the most efficient way to do this for a general n x n numpy array?

Body:
For a readonly version, broadcast_to can be used:

In [370]: x = np.arange(9).reshape(3,3)
In [371]: x
Out[371]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [372]: x = np.broadcast_to(x[..., None],(3,3,10))
In [373]: x
Out[373]:
array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]],

       [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]])

Or with repeat:

In [378]: x=np.repeat(x[...,None],10,2)
In [379]: x
Out[379]:
array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]],

       [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]])

This is a larger array, whose elements can be changed individually.


问:
matchMedia / Javascript Media Query Issue
I created this function to handle the toggle for my mobile nav.

```<code>const mobileNav = document.getElementById('mobile-nav');
let tabs = document.getElementsByClassName('nav_tabs');

//nav toggle control
mobileNav.onclick = (event) => {
 event.preventDefault();
  for(let i = 0; i < tabs.length; i++) {
    if(tabs[i].style.display === "block"){
      tabs[i].style.display = "none";
    } else {
      tabs[i].style.display = "block";
    }
  }
};
</code>```

It's working on great on mobile. The problem is when I resize, the toggle is still set to display none and the toggled menu options are not visible. I have tried using this JS Media Query to reset the display block based on a min-width of 786px but it is not reseting the menu.

```<code>// media query event handler
if (matchMedia) {
const dsktp = window.matchMedia("(min-width: 768px)");
dsktp.addListener(WidthChange);
WidthChange(dsktp);
}

function WidthChange(elem) {
 for(let i = 0; i < elem.length; i++) {
  tabs[i].style.display = "block";
 }
}
</code>```

Here's a codepen of the problem.

答:
Your code does not work because of this code (pay attention to the comments):

```<code>if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange); // <-- add function as handler
  WidthChange(dsktp);
}

function WidthChange(elem) { // elem argument it is not the dom elements here
  for(let i = 0; i < elem.length; i++) {
    tabs[i].style.display = "block";
  }
}
</code>```

So you should rewrite your code this way:

```<code>if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange);
  WidthChange(dsktp);
}

function WidthChange(mediaQueryEvent) {
  for(let i = 0; i < tabs.length; i++) {
    tabs[i].style.display = mediaQueryEvent.matches ? "block" : "none";
  }
}
</code>```

Check my fork of your pen.

Body:
I created this function to handle the toggle for my mobile nav.

const mobileNav = document.getElementById('mobile-nav');
let tabs = document.getElementsByClassName('nav_tabs');

//nav toggle control
mobileNav.onclick = (event) => {
 event.preventDefault();
  for(let i = 0; i < tabs.length; i++) {
    if(tabs[i].style.display === "block"){
      tabs[i].style.display = "none";
    } else {
      tabs[i].style.display = "block";
    }
  }
};

It's working on great on mobile. The problem is when I resize, the toggle is still set to display none and the toggled menu options are not visible. I have tried using this JS Media Query to reset the display block based on a min-width of 786px but it is not reseting the menu.

// media query event handler
if (matchMedia) {
const dsktp = window.matchMedia("(min-width: 768px)");
dsktp.addListener(WidthChange);
WidthChange(dsktp);
}

function WidthChange(elem) {
 for(let i = 0; i < elem.length; i++) {
  tabs[i].style.display = "block";
 }
}

Here's a codepen of the problem.

Body:
Your code does not work because of this code (pay attention to the comments):

if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange); // <-- add function as handler
  WidthChange(dsktp);
}

function WidthChange(elem) { // elem argument it is not the dom elements here
  for(let i = 0; i < elem.length; i++) {
    tabs[i].style.display = "block";
  }
}

So you should rewrite your code this way:

if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange);
  WidthChange(dsktp);
}

function WidthChange(mediaQueryEvent) {
  for(let i = 0; i < tabs.length; i++) {
    tabs[i].style.display = mediaQueryEvent.matches ? "block" : "none";
  }
}

Check my fork of your pen.


问:
Python Pymongo auth failed
Pymongo keep failing to login MongoDB. I typed right password for "root" account.

```<code>Traceback (most recent call last):
  File "index.py", line 3, in <module>
    from apis import app
  File "/home/app/apis/__init__.py", line 16, in <module>
    import apis.call
  File "/home/app/apis/call.py", line 12, in <module>
    import auth
  File "/home/app/apis/auth.py", line 18, in <module>
    connection.api.authenticate(database.ADMIN_ID,database.ADMIN_PASSWD)
  File "/usr/lib64/python2.6/site-packages/pymongo/database.py", line 875, in authenticate
    self.connection._cache_credentials(self.name, credentials)
  File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 456, in _cache_credentials
    auth.authenticate(credentials, sock_info, self.__simple_command)
  File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 243, in authenticate
    auth_func(credentials[1:], sock_info, cmd_func)
  File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 222, in _authenticate_mongo_cr
    cmd_func(sock_info, source, query)
  File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 687, in __simple_command
    helpers._check_command_response(response, None, msg)
  File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 178, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'root'), ('nonce', u'9e44852e6597a1de'), ('key', u'f132369d21874c9858409e235abff25f')]) failed: auth failed
</code>```

Here is pymongo

```<code>import pymongo

connection = pymongo.MongoClient("127.0.0.1")
connection.api.authenticate("root","1234")
db = connection.api
</code>```

does pymongo use md5 on password? it looks like there is some different password in mongodb data.

here is mongodb admin system.users data

{
  "user": "root",
  "pwd": "cde0d84e6749c235a3b4e36d945eb6fe",
  "roles": [
    "userAdminAnyDatabase"
  ]
}

Do you see what is wrong?

答:
Looks like you have to cut the certificate from the Bluemix MongoDB Credentials, save in a file (e.g. certificate.pem), and refer to it as follows:

client = pymongo.MongoClient(uri_string, ssl_ca_certs='c:\data\certificate.pem')

Title: Python Pymongo auth failed

Body:
Pymongo keep failing to login MongoDB. I typed right password for "root" account.

Traceback (most recent call last):
  File "index.py", line 3, in <module>
    from apis import app
  File "/home/app/apis/__init__.py", line 16, in <module>
    import apis.call
  File "/home/app/apis/call.py", line 12, in <module>
    import auth
  File "/home/app/apis/auth.py", line 18, in <module>
    connection.api.authenticate(database.ADMIN_ID,database.ADMIN_PASSWD)
  File "/usr/lib64/python2.6/site-packages/pymongo/database.py", line 875, in authenticate
    self.connection._cache_credentials(self.name, credentials)
  File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 456, in _cache_credentials
    auth.authenticate(credentials, sock_info, self.__simple_command)
  File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 243, in authenticate
    auth_func(credentials[1:], sock_info, cmd_func)
  File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 222, in _authenticate_mongo_cr
    cmd_func(sock_info, source, query)
  File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 687, in __simple_command
    helpers._check_command_response(response, None, msg)
  File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 178, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'root'), ('nonce', u'9e44852e6597a1de'), ('key', u'f132369d21874c9858409e235abff25f')]) failed: auth failed

Here is pymongo

import pymongo

connection = pymongo.MongoClient("127.0.0.1")
connection.api.authenticate("root","1234")
db = connection.api

does pymongo use md5 on password? it looks like there is some different password in mongodb data.

here is mongodb admin system.users data

{
  "user": "root",
  "pwd": "cde0d84e6749c235a3b4e36d945eb6fe",
  "roles": [
    "userAdminAnyDatabase"
  ]
}

Do you see what is wrong?


问:
highcharts is adding an extra day after DST ends when useUtc option is false
Is this a highcharts bug, or am I doing something really dumb? (hover over Nov 6 and compare the xaxis and the tooltip dates)

https://jsfiddle.net/LLExL/8232/

```<code>Highcharts.setOptions({
    global: {
        useUTC: false,
    },
});  // look at the fiddle to see the error going on
</code>```

答:
Nov 5th was daylight savings.  So, it appears some silliness is happening with the date/time and that hour.

I always use UTC with highCharts, so I haven't run into this.  But, it does feel like a bug.

The following with dates in UTC solves the problem.

```<code>Highcharts.setOptions({
    global: {
        useUTC: true,
    },
});

Highcharts.chart('container', {
    xAxis: {
        showLastLabel: true,
        type: 'datetime',
        dateTimeLabelFormats: {
            day: '%b %e',
        },
    },
    series: [{
        data: [
            [Date.UTC(2017,10,1, 0), 0],
            [Date.UTC(2017,10,2, 0), 0],
            [Date.UTC(2017,10,3, 0), 0],
            [Date.UTC(2017,10,4, 0), 0],
            [Date.UTC(2017,10,5, 0), 4],
            [Date.UTC(2017,10,6, 0), 0],
            [Date.UTC(2017,10,7, 0), 0],
            [Date.UTC(2017,10,8, 0), 0],
            [Date.UTC(2017,10,9, 0), 0],
            [Date.UTC(2017,10,10, 0), 0],
        ],
        type: 'line'
    }]
});
</code>```

https://jsfiddle.net/LLExL/8235/

Body:
Is this a highcharts bug, or am I doing something really dumb? (hover over Nov 6 and compare the xaxis and the tooltip dates)

https://jsfiddle.net/LLExL/8232/

Highcharts.setOptions({
    global: {
        useUTC: false,
    },
});  // look at the fiddle to see the error going on

Body:
Nov 5th was daylight savings.  So, it appears some silliness is happening with the date/time and that hour.

I always use UTC with highCharts, so I haven't run into this.  But, it does feel like a bug.

The following with dates in UTC solves the problem.

Highcharts.setOptions({
    global: {
        useUTC: true,
    },
});

Highcharts.chart('container', {
    xAxis: {
        showLastLabel: true,
        type: 'datetime',
        dateTimeLabelFormats: {
            day: '%b %e',
        },
    },
    series: [{
        data: [
            [Date.UTC(2017,10,1, 0), 0],
            [Date.UTC(2017,10,2, 0), 0],
            [Date.UTC(2017,10,3, 0), 0],
            [Date.UTC(2017,10,4, 0), 0],
            [Date.UTC(2017,10,5, 0), 4],
            [Date.UTC(2017,10,6, 0), 0],
            [Date.UTC(2017,10,7, 0), 0],
            [Date.UTC(2017,10,8, 0), 0],
            [Date.UTC(2017,10,9, 0), 0],
            [Date.UTC(2017,10,10, 0), 0],
        ],
        type: 'line'
    }]
});

https://jsfiddle.net/LLExL/8235/


问:
How to order a list of objects using a list of object attributes
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

```<code>ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break
</code>```

答:
You can use sorted function with custom sorting function. In this case returning index in the ids list.

```<code>def order_by(objects, ids):
    def fn(obj):
        return ids.index(obj["id"])

    return sorted(objects, key=fn)

print(order_by(objects_list, id_list))
</code>```

Example:

```<code>objects_list = [
{ "id": 3, "name": "penny"},
{ "id": 5, "name": "adam"},
{ "id": 9, "name": "meh"},
{ "id": 1, "name": "john"},
{ "id": 3, "name": "archibald"},
]
id_list = [9,1,3,5,6,4]

print(order_by(objects_list, id_list))
</code>```

Results in:

```<code>[{'id': 9, 'name': 'meh'}, {'id': 1, 'name': 'john'}, {'id': 3, 'name': 'penny'}, {'id': 3, 'name': 'archibald'}, {'id': 5, 'name': 'adam'}]
</code>```

Body:
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break

Body:
You can use sorted function with custom sorting function. In this case returning index in the ids list.

def order_by(objects, ids):
    def fn(obj):
        return ids.index(obj["id"])

    return sorted(objects, key=fn)

print(order_by(objects_list, id_list))

Example:

objects_list = [
{ "id": 3, "name": "penny"},
{ "id": 5, "name": "adam"},
{ "id": 9, "name": "meh"},
{ "id": 1, "name": "john"},
{ "id": 3, "name": "archibald"},
]
id_list = [9,1,3,5,6,4]

print(order_by(objects_list, id_list))

Results in:

[{'id': 9, 'name': 'meh'}, {'id': 1, 'name': 'john'}, {'id': 3, 'name': 'penny'}, {'id': 3, 'name': 'archibald'}, {'id': 5, 'name': 'adam'}]


问:
Swift - Navigation Bars
I am having trouble making it so that the navigation bar will have an optimised display for both the iPhone X and all other iPhones and iPads.

I have read on the apple developer documentation that the navigation bar is meant to adapt so that the title is not hidden by the sensor housing on the iPhone X.

I have therefore tried making a navigation bar as normal on an iPhone 8 on the Interface Builder (and adding height 65 constraints, as well as top, left and right attachment constraints).

When I run in the simulator, the iPhone X shows the navigation bar through the sensor housing, thus meaning the title isn't visible.

Any help on how to get navigation bars working for all iPhones and iPads and the iPhone X at the same time would be much appreciated.

Thanks in advance :)

答: As of iOS 11 you are supposed to be using the new safe area guides to position your content.  Do not assume a bar size as an offset from your view.  See the apple documentation on Positioning Content Relative to the Safe Area</p>

Title: Swift - Navigation Bars


问:
Trouble compiling for iOS 11.1 with Xamarin (Visual Studio)
There is not much of a point in posting actual code here, because we're talking about 7 different apps.

All of these apps have been up on the Apple Store and running fine.  Until the new iOS 11.1 came out.  Now I am being forced to update all of those apps, and rearrange the screen to allow for the new layout of the iPhone X.

Now all of this seems mostly reasonable, if not ridiculous for them changing their own design standard.  But the real problem is that I went through all of that.  Upgraded Xamarin (Visual Studio), and packages, and Xcode, and the Simulators, AND my Mac system.  Everything is up to speed.  The apps compile and test fine on any simulator I install them on.

The only change to the code is moving stuff around on the screen.  Well, that, and I now need to drop support for anything i386.  It all has to be x86_64 now.

From what I can tell, that is a difference from 32-bit to 64-bit.  And that change is a dropdown menu choice in the Project Options.  In any case, there is no indication at all that there is anything wrong with these apps at all.

So with all of this, I submit my apps for approval, and every single one of them gets rejected because "The app crashes on startup."  And they kindly attach a log file showing what went wrong.

Now, I know I can simply scour those logs, for all 7 apps... The log files need to be fed into some other program that can decipher them, because they are not human-readable.  Which is just annoying...

What I'm hoping is that someone can save me some trouble and explain what they changed in their systems that is not being caught by the compilers or the simulators.

Any help would be hot.

答:
I am posting my own answer because I have not seen one anywhere that addresses what I have found to have worked.  So I am providing this information for the next small developer, like myself, can get some useful answers to questions where Apple and Xamarin are simply NO HELP at all.

Xamarin does provide a page that essentially says, "get your app ready for iOS 11."  The most useful part of this is where it shows you how to remove any linkage to anything 32-bit.

Architecture changes

This is mostly helpful.  And I thought that once that was done, I'd be all set.  There are 2 other things they completely fail to mention:
- You must set your target device to 11.1.  You cannot have it set for 9.0.  That will make the app crash on an 11.1 system.
- You must make a change in the manual code editing (source) section of the info.plst file.  Why this is not done automatically, I cannot say.  You must add an entry to the "Required Device Capabilities" section for "arm64".  You also must remove the one for arm7.

Failure to do these two things, even after making their suggested changes will cause the app to crash on iOS 11.1 devices.

If you think I'm having a bit of an attitude problem about this, yes, I am.  And I will not apologize for it.

It is absurd for Apple to change their design specs, give us very little time to make changes, and then not provide the absolutely essential information to actually make the changes.  I blame Xamarin too.  For the exact same reasons.

It is also absurd to totally deprecate all the testing devices I have, and then ask, "why don't you test on an actual device?"  Because I cannot afford a new $1000 phone for the sake of testing apps that barely make me any money anyway.  That's why.

And people wonder why I think it's a pain in the bum to develop for iOS devices.


问:
Why does Google Cloud Function run a global function multiple times after deploy?
I have set multiple triggers, like:

```<code>exports.doSomething = functions.firestore.document('col/{doc}').onCreate(event => {})
</code>```

Than I have a function that I want to run instant when I deployed. That looks something like this:

```<code>now()
function now(){
    console.log("running function")
}
</code>```

And I get this in my logs:

Why does it run so many times and gets called by other functions?

Full code, just tested it and running function gets called 4 times, the same amount as triggers I have set:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore()
var geoip = require('geoip-lite');

exports.z = functions.firestore.document('converasdassdtIP/{UID}').onCreate(event => { })
exports.x = functions.firestore.document('sads/{UID}').onCreate(event => { })
exports.n = functions.firestore.document('asdasasdsa/{UID}').onCreate(event => { })
exports.m = functions.firestore.document('converasdasddtIP/{UID}').onCreate(event => { })

now()
function now(){
    console.log("running function")
}
</code>```

答:
Cloud Functions doesn't provide a way to run a bit of code at the time of deploy.  Your function is obviously being run multiple times, and you should expect it to be run even more times as new server instances are allocated (and destroyed) in tandem with the load on your project.  This is how Cloud Functions scales.  There is definitely not just one server instance handling all your requests.  You should expect any global code to be run repeatedly.

If you want to run some code exactly once after deploy, make an exported funciton (maybe HTTPS) and trigger it after you deploy.  Maybe you could write a script that both deploys your code then triggers the function with curl or some other mechanism you choose.

Body:
I have set multiple triggers, like:

exports.doSomething = functions.firestore.document('col/{doc}').onCreate(event => {})

Than I have a function that I want to run instant when I deployed. That looks something like this:

now()
function now(){
    console.log("running function")
}

And I get this in my logs:

Why does it run so many times and gets called by other functions?

Full code, just tested it and running function gets called 4 times, the same amount as triggers I have set:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore()
var geoip = require('geoip-lite');

exports.z = functions.firestore.document('converasdassdtIP/{UID}').onCreate(event => { })
exports.x = functions.firestore.document('sads/{UID}').onCreate(event => { })
exports.n = functions.firestore.document('asdasasdsa/{UID}').onCreate(event => { })
exports.m = functions.firestore.document('converasdasddtIP/{UID}').onCreate(event => { })

now()
function now(){
    console.log("running function")
}


问:
$.post submitting form before inner Ajax can run
I'm not sure if its the best practice to do this but I've got an $.post with an Ajax inside. The issue is if I remove the return false from the $.post then the form will submit before Ajax can run.

```<code>$(".buy").submit(function(e) {

  var url = "http://perfectprints.org.uk/Canvas/js/send_email.php";

  html2canvas($('.canvas-cut')).then(function(canvas) {

    $('canvas').addClass('canvas-layout');
    var src = canvas.toDataURL();
    var output = src.replace(/^data:image\/(png|jpg);base64,/, "");
    $.post('image.php', {
      data: output
    }).done(function(response) {
      alert("Done");
      $.ajax({
        type: "POST",
        url: url,
        data: {
          shape: shape,
          finish: finish,
          ori: ori,
          current_width: current_width,
          current_height: current_height
        },
        success: function(data) {
          $('html,body').scrollTop(0);
        }
      });
    });

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

This will only work if return false is in place to stop $.post from firing.
I've attempted to try to submit the form after ajax has finished but it wouldn't work.

Any help or advice would be most welcome.

Thank you.

答:
Use a button with type button and id.

This element not submit the form data by default and could be used to make Ajax calls.

```<code><button id="button_buy" type="button">Buy</button>
</code>```

Then add a event click to this button and use the actual code of submit event.

```<code>$("#button_buy").click(function(e) {
    //code of $(".buy").submit

    //inside ajax success fire submit event's form
    //$('the_form).submit();

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

Body:
I'm not sure if its the best practice to do this but I've got an $.post with an Ajax inside. The issue is if I remove the return false from the $.post then the form will submit before Ajax can run.

$(".buy").submit(function(e) {

  var url = "http://perfectprints.org.uk/Canvas/js/send_email.php";

  html2canvas($('.canvas-cut')).then(function(canvas) {

    $('canvas').addClass('canvas-layout');
    var src = canvas.toDataURL();
    var output = src.replace(/^data:image\/(png|jpg);base64,/, "");
    $.post('image.php', {
      data: output
    }).done(function(response) {
      alert("Done");
      $.ajax({
        type: "POST",
        url: url,
        data: {
          shape: shape,
          finish: finish,
          ori: ori,
          current_width: current_width,
          current_height: current_height
        },
        success: function(data) {
          $('html,body').scrollTop(0);
        }
      });
    });

  });
  return false;
});

This will only work if return false is in place to stop $.post from firing.
I've attempted to try to submit the form after ajax has finished but it wouldn't work.

Any help or advice would be most welcome.

Thank you.

Body:
Use a button with type button and id.

This element not submit the form data by default and could be used to make Ajax calls.

<button id="button_buy" type="button">Buy</button>

Then add a event click to this button and use the actual code of submit event.

$("#button_buy").click(function(e) {
    //code of $(".buy").submit

    //inside ajax success fire submit event's form
    //$('the_form).submit();

    //delete return false
});


问:
Organize Cloud Functions for Firebase
What is the best practice to organize all our Cloud Functions for Firebase?

I see from the sample GitHub repository that all functions reside in a single index.js file.

I guess for bigger project that there is a better approach to organize  Cloud Functions for Firebase in different files/directory.

答:
You could use something like export { functionName } from './file' at your index.js file.

/functions/index.js

```<code>// This is the main entry point for the app written in ES that is compatible with node lts
import * as functions from 'firebase-functions';

export { sendWelcomeEmail } from './userEmails';

exports.helloWorld = functions.https.onRequest((request, response) => {
  let helloMsg = `Hello!`;
  response.send(helloMsg);
});
</code>```

Title: Organize Cloud Functions for Firebase

Body:
You could use something like export { functionName } from './file' at your index.js file.

/functions/index.js

// This is the main entry point for the app written in ES that is compatible with node lts
import * as functions from 'firebase-functions';

export { sendWelcomeEmail } from './userEmails';

exports.helloWorld = functions.https.onRequest((request, response) => {
  let helloMsg = `Hello!`;
  response.send(helloMsg);
});


问:
Date's prototype methods are not enumerable. How to obtain a list of them to iterate?
I want to iterate over the methods of a javascript Date object.  The first attempt did not work:

```<code>var date = new Date();
for (var key in date) {
    console.log(key);
}
</code>```

I've tried a few related things -- Object.keys, for example.  So far I have not found a way to do it.

答:
From MDN:

The Object.getOwnPropertyNames() method returns an array of all
  properties (including non-enumerable properties except properties that
  using Symbol) found directly upon a given object.

So Object.getOwnPropertyNames will produce the list I was looking for when called directly on the prototype object:

```<code>Object.getOwnPropertyNames(Date.prototype)
</code>```

Body:
I want to iterate over the methods of a javascript Date object.  The first attempt did not work:

var date = new Date();
for (var key in date) {
    console.log(key);
}

I've tried a few related things -- Object.keys, for example.  So far I have not found a way to do it.

Body:
From MDN:

The Object.getOwnPropertyNames() method returns an array of all
  properties (including non-enumerable properties except properties that
  using Symbol) found directly upon a given object.

So Object.getOwnPropertyNames will produce the list I was looking for when called directly on the prototype object:

Object.getOwnPropertyNames(Date.prototype)


问:
AfterGlowPlayer after setting dynamically data-youtube-id video won't play
I im using this video player:

http://docs.afterglowplayer.com/docs/playing-a-youtube-video

and after i dynamically add data-youtube-id i im unable to play video..do i need call with another way?

my script of reading glowplayer2 class and appending it to glowplayer3 class that can center glowplayer on the screen (glowplayer2 class is hidden div that contains php generated url)

```<code>$(".afterglowplayer2").click(function () {
     switch(true) {
       case /imdb/.test($("#myvideo video", this).attr("src")):
          alert("IMDB!");
          $(".afterglowplayer3 #myvideo video").attr("src", $("#myvideo video", this).attr("src"))
          break;
       default:
          alert("YOUTUBE");
          $(".afterglowplayer3 #myvideo video").attr("data-youtube-id", $("#myvideo video", this).attr("src")).removeAttr("src");
          break;
     }
     $.afterglowplayer.toggle(".afterglowplayer3");
     return false;
  });
</code>```

After that code i get this:

```<code><video class="vjs-tech" id="myvideo_html5_api" data-ratio="0.5625" style="padding-top: 56.25%;" preload="auto" data-youtube-id="XpICoc65uh0"></video>
</code>```

So you see that correct data-youtube-id is set using above jQuery function but video is not playing...why? If i set it manually in html code it plays normally...but i need to change and remove src if is youtube video and if is not add src attribute to video tag...

答:
You should put their respective class (afterglow) and size

```<code><video class="afterglow vjs-tech" width="960" height="540"...
</code>```

edit Your code -> is misspelled.

```<code>$(".afterglowplayer2").click(function () {
   if(/imdb/.test($("#uniqueid", this).attr("src")){
      alert("IMDB!");
      $("#uniqueid").attr("src", $("#uniqueid", this).attr("src"))
   } else {
      alert("YOUTUBE");
      $("#uniqueid").attr("data-youtube-id", $("#uniqueid", this).attr("src")).removeAttr("src");
   }
   $.afterglowplayer.toggle(".afterglowplayer3");
   return false;
});
</code>```

Body:
I im using this video player:

http://docs.afterglowplayer.com/docs/playing-a-youtube-video

and after i dynamically add data-youtube-id i im unable to play video..do i need call with another way?

my script of reading glowplayer2 class and appending it to glowplayer3 class that can center glowplayer on the screen (glowplayer2 class is hidden div that contains php generated url)

$(".afterglowplayer2").click(function () {
     switch(true) {
       case /imdb/.test($("#myvideo video", this).attr("src")):
          alert("IMDB!");
          $(".afterglowplayer3 #myvideo video").attr("src", $("#myvideo video", this).attr("src"))
          break;
       default:
          alert("YOUTUBE");
          $(".afterglowplayer3 #myvideo video").attr("data-youtube-id", $("#myvideo video", this).attr("src")).removeAttr("src");
          break;
     }
     $.afterglowplayer.toggle(".afterglowplayer3");
     return false;
  });

After that code i get this:

<video class="vjs-tech" id="myvideo_html5_api" data-ratio="0.5625" style="padding-top: 56.25%;" preload="auto" data-youtube-id="XpICoc65uh0"></video>

So you see that correct data-youtube-id is set using above jQuery function but video is not playing...why? If i set it manually in html code it plays normally...but i need to change and remove src if is youtube video and if is not add src attribute to video tag...

Body:
You should put their respective class (afterglow) and size

<video class="afterglow vjs-tech" width="960" height="540"...

edit Your code -> is misspelled.

$(".afterglowplayer2").click(function () {
   if(/imdb/.test($("#uniqueid", this).attr("src")){
      alert("IMDB!");
      $("#uniqueid").attr("src", $("#uniqueid", this).attr("src"))
   } else {
      alert("YOUTUBE");
      $("#uniqueid").attr("data-youtube-id", $("#uniqueid", this).attr("src")).removeAttr("src");
   }
   $.afterglowplayer.toggle(".afterglowplayer3");
   return false;
});


问:
Extracting a text file from tar with tarfile module in python3
Is there a simple way to extract a text file from a tar file as a file object of text I/O in python 3.4 or later?

I am revising my python2 code to python3, and I found TarFile.extractfile, which used to return a file object with text I/O, now returns a io.BufferedReader object which seems to have binary I/O. The other part of my code expects a text I/O, and I need to absorb this change in some way.

One method I can think of is to use TarFile.extract and write the file to a directory, and open it by open function, but I wonder if there is a way to get the text I/O stream directly.

答: Try io.TextIOWrapper to wrap the io.BufferedReader.


问:
How to remove unused objects after matching with another array?
I have an array of objects and another array of names like the following:

array of objects as file info objects

```<code>[
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo'  , path: 'logo_img_path'   },
  { fieldname: 'random', path: 'random_img_path' }
]
</code>```

and here is my array of names

```<code>['banner', 'logo']
</code>```

So how can i match or mapping those two variables! note that after mapping or matching, all not used objects should be deleted from the original array of objects?? i need to get object like that

```<code>{
  banner: banner_img_path,
  logo  : logo_img_path
}
</code>```

I'm able to do matching but i was stuck with erasing those not used objects.

Note: May be this question is duplicated but only because i don't know what is the name of this operation!
so please forgive me.

答:
I add the names you want to keep into a set for lookup. I then use forEach and check inside each object if the fieldname matches anything in the set of names. If there's a match, I add it to my newObj.

const namesToKeep = ['banner', 'logo']
const fileInfo = [
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo'  , path: 'logo_img_path'   },
  { fieldname: 'random', path: 'random_img_path' }
]

const names = new Set(namesToKeep)
const newObj = {}

fileInfo.forEach(obj => {
  if (names.has(obj.fieldname)) {
    newObj[obj.fieldname] = obj.path
  }
})
console.log(newObj)```

Body:
I have an array of objects and another array of names like the following:

array of objects as file info objects

[
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo'  , path: 'logo_img_path'   },
  { fieldname: 'random', path: 'random_img_path' }
]

and here is my array of names

['banner', 'logo']

So how can i match or mapping those two variables! note that after mapping or matching, all not used objects should be deleted from the original array of objects?? i need to get object like that

{
  banner: banner_img_path,
  logo  : logo_img_path
}

I'm able to do matching but i was stuck with erasing those not used objects.

Note: May be this question is duplicated but only because i don't know what is the name of this operation!
so please forgive me.


问:
Function in button
So I'm working on a wordpress theme and it's really twisted. The problem is I'm comfortable just with html and css, as I'm a code noob, so I would really appreciate your help here.

The problem here is that I want to put a tracking script and a redirect on a specific button. I'd now how to do this if I'd find the button's html form.

But when I go to the code in the page where the button is, this is the only thing showing regarding the button

```<code>    <?php BookYourTravel_Theme_Utils::render_submit_button("primary-btn",
    "submit-accommodation-booking", esc_html__('TRIMITE REZERVAREA',
    'bookyourtravel')); ?>
</code>```

BookYourTravel is the theme

I know you should maybe see all the files to know what to do, as this doesn't seem as enough info.
But I also have a functions.php file. Should I look there? Do you have any idea where should I go?

Thank you a lot. Really stuck here.

答:
Are you writing the theme yourself or are you working with someone else's theme? If you're working on someone else's theme, I would reccommend looking into building a child theme so if you change some code, the OG theme is still there in it's entirety and if they update the theme, your code wont get destroyed in the update. There are tons of tutorials on how to set up a child theme and theres a plugin that will make it for you called Child Theme Configurator if you're not too keen on doing it yourself. </p>

<p>You should be super careful when you're editing functions in your theme(especially if you're new to PHP), but that's where this html is being generated. One of those functions is the thing that's generating your html. If you find where the function is held, you could probably change it so it echos the extra code you're looking to implement but it would be on every button that this function generates throughout your site.  </p>

Title: Function in button

Body:
So I'm working on a wordpress theme and it's really twisted. The problem is I'm comfortable just with html and css, as I'm a code noob, so I would really appreciate your help here.

The problem here is that I want to put a tracking script and a redirect on a specific button. I'd now how to do this if I'd find the button's html form.

But when I go to the code in the page where the button is, this is the only thing showing regarding the button

    <?php BookYourTravel_Theme_Utils::render_submit_button("primary-btn",
    "submit-accommodation-booking", esc_html__('TRIMITE REZERVAREA',
    'bookyourtravel')); ?>

BookYourTravel is the theme

I know you should maybe see all the files to know what to do, as this doesn't seem as enough info.
But I also have a functions.php file. Should I look there? Do you have any idea where should I go?

Thank you a lot. Really stuck here.

Body:
Are you writing the theme yourself or are you working with someone else's theme? If you're working on someone else's theme, I would reccommend looking into building a child theme so if you change some code, the OG theme is still there in it's entirety and if they update the theme, your code wont get destroyed in the update. There are tons of tutorials on how to set up a child theme and theres a plugin that will make it for you called Child Theme Configurator if you're not too keen on doing it yourself.

You should be super careful when you're editing functions in your theme(especially if you're new to PHP), but that's where this html is being generated. One of those functions is the thing that's generating your html. If you find where the function is held, you could probably change it so it echos the extra code you're looking to implement but it would be on every button that this function generates throughout your site.


问:
Dealing with commas in a CSV file
I am looking for suggestions on how to handle a csv file that is being created, then uploaded by our customers, and that may have a comma in a value, like a company name.

Some of the ideas we are looking at are: quoted Identifiers (value "," values ","etc) or using a | instead of a comma.  The biggest problem is that we have to make it easy, or the customer won't do it.

答:
The simplest solution I've found is the one LibreOffice uses:

Replace all literal " by ”

Put double quotes around your string

You can also use the one that Excel uses:

Replace all literal " by ""

Put double quotes around your string

Notice other people recommended to do only step 2 above, but that doesn't work with lines where a " is followed by a ,, like in a CSV where you want to have a single column with the string hello",world, as the CSV would read:

```<code>"hello",world"
</code>```

Which is interpreted as a row with two columns: hello and world"

Title: Dealing with commas in a CSV file

Body:
The simplest solution I've found is the one LibreOffice uses:

Replace all literal " by ”

Put double quotes around your string

You can also use the one that Excel uses:

Replace all literal " by ""

Put double quotes around your string

Notice other people recommended to do only step 2 above, but that doesn't work with lines where a " is followed by a ,, like in a CSV where you want to have a single column with the string hello",world, as the CSV would read:

"hello",world"

Which is interpreted as a row with two columns: hello and world"