问:
adding some jquery script to Magento page
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

```<code>$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
</code>```

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

答:
If you've added the jQuery library and turned on noConflict mode, then you should try accessing the jQuery object using the jQuery variable as opposed to the $ variable. Try it like this and see if it works:

```<code>jQuery(document).ready(function(){
    jQuery("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
</code>```

If that doesn't work, you should double check your html output to see if the jQuery library is being included before you script is running. This is crucial as JavaScript processes sequentially on a page from top to bottom.

Body:
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

Body:
If you've added the jQuery library and turned on noConflict mode, then you should try accessing the jQuery object using the jQuery variable as opposed to the $ variable. Try it like this and see if it works:

jQuery(document).ready(function(){
    jQuery("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

If that doesn't work, you should double check your html output to see if the jQuery library is being included before you script is running. This is crucial as JavaScript processes sequentially on a page from top to bottom.


来源: stackexchange

问:
Call function when control is shown
I have input control:

```<code><input id="someID" class="form-control" type="text" name="SomeData"
data-ng-model="vm.SomeData">
</code>```

and I need to initialize value vm.SomeData when user will scroll down to this control. I am new in angular, so not sure is there some event like 'ControlDisplayed'?

答:
```<code> //html
<input id="someID" when-scrolled="vm" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData">

//try this directive
app.directive("whenScrolled", function(){
  return {
    restrict: 'A',
    link: function(scope, elem, attrs){
    // we get a list of elements of size 1 and need the first element
    raw = elem[0];
    // we load more elements when scrolled past a limit
    elem.bind("scroll", function(){
      if(raw.scrollTop+raw.offsetHeight+5 >= raw.scrollHeight){
           scope.vm.name = 'Nainish Modi';
         // we can give any function which loads more elements into the list
           scope.$apply(attrs.whenScrolled);
         }
       });
      }
    }
 });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Call function when control is shown

Body:
I have input control:

<input id="someID" class="form-control" type="text" name="SomeData"
data-ng-model="vm.SomeData">

and I need to initialize value vm.SomeData when user will scroll down to this control. I am new in angular, so not sure is there some event like 'ControlDisplayed'?


问:
Newbie SQL error; missing expression
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

```<code>select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;
</code>```

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

答:
You can use a standard sub-query as you are attempting in your question;

```<code>SELECT s.sa_id
FROM   cisadm.ci_sa s
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'
AND    s.sa_id IN (SELECT pf.sa_id
                   FROM   cisadm.ci_intv_pf pf
                   WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI')
</code>```

A correlated sub-query is also possible using EXISTS:

```<code>SELECT s.sa_id
FROM   cisadm.ci_sa s
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'
AND    s.sa_id EXISTS (SELECT 1
                       FROM   cisadm.ci_intv_pf pf
                       WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI'
                       AND    pf.sa_id = s.sa_id)
</code>```

And then there's using WITH to refactor the sub-query which can make complex queries a bit easier to read;

```<code>WITH sub_query AS
(SELECT 1
 FROM   cisadm.ci_intv_pf pf
 WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI')
SELECT  s.sa_id
FROM   cisadm.ci_sa s
       INNER JOIN
       sub_query pf ON pf.sa_id = s.sa_id
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'
</code>```

There will likely be some differences in efficiency for all these based largely on the relative sizes of the tables but Oracle does a pretty good job of picking the most efficient way nowadays.

Caveat: I haven't actually set up tables and data to test these

Title: Newbie SQL error; missing expression

Body:
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

Body:
You can use a standard sub-query as you are attempting in your question;

SELECT s.sa_id
FROM   cisadm.ci_sa s
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'
AND    s.sa_id IN (SELECT pf.sa_id
                   FROM   cisadm.ci_intv_pf pf
                   WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI')

A correlated sub-query is also possible using EXISTS:

SELECT s.sa_id
FROM   cisadm.ci_sa s
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'
AND    s.sa_id EXISTS (SELECT 1
                       FROM   cisadm.ci_intv_pf pf
                       WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI'
                       AND    pf.sa_id = s.sa_id)

And then there's using WITH to refactor the sub-query which can make complex queries a bit easier to read;

WITH sub_query AS
(SELECT 1
 FROM   cisadm.ci_intv_pf pf
 WHERE  pf.intv_pf_typ_cd = 'SMPCHGRI')
SELECT  s.sa_id
FROM   cisadm.ci_sa s
       INNER JOIN
       sub_query pf ON pf.sa_id = s.sa_id
WHERE  s.sa_status_flg = '20'
AND    s.sa_type_cd = 'LEURIBIL'

There will likely be some differences in efficiency for all these based largely on the relative sizes of the tables but Oracle does a pretty good job of picking the most efficient way nowadays.

Caveat: I haven't actually set up tables and data to test these


问:
git credneital-manager-st is not a git command on Windows 10
When I run the command

```<code> git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=manager-st push -v --tags origin Br123:Br123
</code>```

I get the error

```<code>git: 'credential-manager-st' is not a git command. See 'git --help'.
error: failed to push some refs to 'http://host'
</code>```

I am running Windows 10 Version 1703 with git version 2.13.2.windows.1   The command is originally from SourceTree (v2.0.20.1).

Despite various debugging and checking the Windows Credential Manager, I am having no success in resolving the issue.

I can push/sync directly from Visual Studio 2015. I believe this uses library calls and not git.exe.

答:
It could be a problem that you try to use the git credential manager on Windows.

I found this open-source tool (https://github.com/Microsoft/Git-Credential-Manager-for-Windows) which can be installed and used afterwards like this:

```<code>git credential-manager [<command> [<args>]]
</code>```

Body:
When I run the command

 git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=manager-st push -v --tags origin Br123:Br123

I get the error

git: 'credential-manager-st' is not a git command. See 'git --help'.
error: failed to push some refs to 'http://host'

I am running Windows 10 Version 1703 with git version 2.13.2.windows.1   The command is originally from SourceTree (v2.0.20.1).

Despite various debugging and checking the Windows Credential Manager, I am having no success in resolving the issue.

I can push/sync directly from Visual Studio 2015. I believe this uses library calls and not git.exe.

Body:
It could be a problem that you try to use the git credential manager on Windows.

I found this open-source tool (https://github.com/Microsoft/Git-Credential-Manager-for-Windows) which can be installed and used afterwards like this:

git credential-manager [<command> [<args>]]


问:
How MSP,Consensus, Ordering service is pluggable in Hyperledger Fabric?
As Hyperledger Fabric architecture is modular, How can I plug in the modules like MSP, Consensus and Ordering Service.</p>

答:
For MSP all you need to do is implement your own MSP implementation and make it implement the MSP interface

For Consensus/Ordering service, you need to have a gRPC service that provides the AtomicBroadcast service.


问:
Ruby variable in Postgresql Regex
I have a table named orders with a column named comment in it.

I have a list of order ids, and I want to search through all the comment to see which order has referenced them.

So far I have worked out the regex part of the sql

```<code>Order.where('comment ~ \'\s\d{5}\' OR comment ~ \'^\d{5}\'')
     .where("comment LIKE '%?%'", order_id)
</code>```

But I can't seem to work out a way to make the query more flexible to find order_ids that have different length other than 5

Is it possible to make {5} more dynamic, to something like {#{order_id.to_s.length}}?

UPDATE
Just ran into this post
Using a boundary match would work even better for this case.

Order.where('comment ~ \'\y?\y\'', order_id)
Would do the trick.

答:
We can pass digit_count

```<code>digit_count = order_id.to_s.length
Order.where('comment ~ \'\s\d{?}\' OR comment ~ \'^\d{?}\'', digit_count, digit_count)
</code>```

if you are looking for specific order_id

```<code>Order.where("comment ~ \'\s#{order_id}\s\'")
</code>```

Title: Ruby variable in Postgresql Regex

Body:
I have a table named orders with a column named comment in it.

I have a list of order ids, and I want to search through all the comment to see which order has referenced them.

So far I have worked out the regex part of the sql

Order.where('comment ~ \'\s\d{5}\' OR comment ~ \'^\d{5}\'')
     .where("comment LIKE '%?%'", order_id)

But I can't seem to work out a way to make the query more flexible to find order_ids that have different length other than 5

Is it possible to make {5} more dynamic, to something like {#{order_id.to_s.length}}?

UPDATE
Just ran into this post
Using a boundary match would work even better for this case.

Order.where('comment ~ \'\y?\y\'', order_id)
Would do the trick.

Body:
We can pass digit_count

digit_count = order_id.to_s.length
Order.where('comment ~ \'\s\d{?}\' OR comment ~ \'^\d{?}\'', digit_count, digit_count)

if you are looking for specific order_id

Order.where("comment ~ \'\s#{order_id}\s\'")


问:
linq to sql optimized a group with multiple joins
I need help generating a more efficient LINQ query:

```<code>Table: Positions
-PositionID
-Name

Table: Person
-PersonID
-Name, etc...

Table: PersonPosition
-PersonID
-PositionID
</code>```

I need a result set that groups the people assigned to each position:

```<code>PositionID  Person
1           John
            Bob
            Frank

2           Bill
            Tom
            Frank, etc...
</code>```

My first thought was this LINQ query:

```<code>from perspos in PersonPositions
join pers in Persons            on perspos.PersonID equals pers.PersonID
group pers by perspos.PositionID into groups
select new {groups.Key, groups}
</code>```

Which works great, but produces the following SQL:

```<code>SELECT [t0].[PositionID] AS [Key]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
GROUP BY [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 3
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 4
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 5
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

on and on...
</code>```

Is there a better LINQ query that translates to a more efficient SQL statement?

答:
I'm fairly sure you have to just join the tables and select the result, then call .AsEnumerable(), and group after that:</p>

```<code>(from perspos in PersonPositions
 join pers in Persons
 on perspos.PersonID equals pers.PersonID
 select new { perspos.PositionID, Person = pers })
.AsEnumerable().GroupBy(p => p.PositionID, p => p.Person);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need help generating a more efficient LINQ query:

Table: Positions
-PositionID
-Name

Table: Person
-PersonID
-Name, etc...

Table: PersonPosition
-PersonID
-PositionID

I need a result set that groups the people assigned to each position:

PositionID  Person
1           John
            Bob
            Frank

2           Bill
            Tom
            Frank, etc...

My first thought was this LINQ query:

from perspos in PersonPositions
join pers in Persons            on perspos.PersonID equals pers.PersonID
group pers by perspos.PositionID into groups
select new {groups.Key, groups}

Which works great, but produces the following SQL:

SELECT [t0].[PositionID] AS [Key]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
GROUP BY [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 3
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 4
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 5
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

on and on...

Is there a better LINQ query that translates to a more efficient SQL statement?

Body:
I'm fairly sure you have to just join the tables and select the result, then call .AsEnumerable(), and group after that:

(from perspos in PersonPositions
 join pers in Persons
 on perspos.PersonID equals pers.PersonID
 select new { perspos.PositionID, Person = pers })
.AsEnumerable().GroupBy(p => p.PositionID, p => p.Person);


问:
Call on_press callback multiple times on key held down event
I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..

```<code>import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError:
            print 'warning: dropped frame' # can replace with 'pass' if no message desired
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
</code>```

I am using pynput for keyboard events and pyaudio for recording.
it seems to record when cmd_l is pressed down and stops when i release. problem is the audio file generated doesn't contain anything, or is pretty short as in 0.19s long.

I guess it could have to do with stream.read has to be called multiple times, and the keypress is only being recorded once hence only one sample is being recorded.

but if that is the case how do i make it call stream.read multiple times, while also detecting also detecting when it is being released?
or are there libraries that support on_hold mechanism on keyboards?

Updated approach with threading:

```<code>from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False
</code>```

I tried a different approach introducing two threads, which one monitoring the keyboard, and the other one sorts out the recording. But this solution keeps dropping the frames, hence nothing is actually being recorded?..

how come?

答:
Here's an example of how you might do it: I have modified your code by making a separate thread do the recording. The keyboard press/release sets the state of an Event, and the thread records chunks in a loop when the Event is set. A separate Event is used to tell the thread to terminate after recording is done. This records multiple 32Kb chunks for me (8192 * 2 chans * 16 bits).

```<code>import pyaudio
import wave
from pynput import keyboard
import threading

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

recordingEvent = threading.Event()    # set to activate recording
exitEvent = threading.Event()         # set to stop recording thread

def on_press(key):
    if key == keyboard.Key.ctrl:
        print('- Started recording -'.format(key))
        recordingEvent.set()
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.ctrl:
        print('{0} stop'.format(key))
        recordingEvent.clear()
        keyboard.Listener.stop
        return False

def do_recording():
    while (not exitEvent.is_set()):
        if (recordingEvent.wait(0.1)):
            try:
                data = stream.read(CHUNK)
                # print len(data)
                frames.append(data)
            except IOError:
                print 'warning: dropped frame' # can replace with 'pass' if no message desired

class myRecorder(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        do_recording()

# start recorder thread
recordingThread = myRecorder()
recordingThread.start()

# monitor keyboard
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

# stop recorder thread
exitEvent.set()
recordingThread.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
</code>```

NB I used the Ctrl key instead of the Cmd key, as it suited my machine better. Hope this is useful.

Body:
I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..

import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError:
            print 'warning: dropped frame' # can replace with 'pass' if no message desired
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

I am using pynput for keyboard events and pyaudio for recording.
it seems to record when cmd_l is pressed down and stops when i release. problem is the audio file generated doesn't contain anything, or is pretty short as in 0.19s long.

I guess it could have to do with stream.read has to be called multiple times, and the keypress is only being recorded once hence only one sample is being recorded.

but if that is the case how do i make it call stream.read multiple times, while also detecting also detecting when it is being released?
or are there libraries that support on_hold mechanism on keyboards?

Updated approach with threading:

from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False

I tried a different approach introducing two threads, which one monitoring the keyboard, and the other one sorts out the recording. But this solution keeps dropping the frames, hence nothing is actually being recorded?..

how come?

Body:
Here's an example of how you might do it: I have modified your code by making a separate thread do the recording. The keyboard press/release sets the state of an Event, and the thread records chunks in a loop when the Event is set. A separate Event is used to tell the thread to terminate after recording is done. This records multiple 32Kb chunks for me (8192 * 2 chans * 16 bits).

import pyaudio
import wave
from pynput import keyboard
import threading

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

recordingEvent = threading.Event()    # set to activate recording
exitEvent = threading.Event()         # set to stop recording thread

def on_press(key):
    if key == keyboard.Key.ctrl:
        print('- Started recording -'.format(key))
        recordingEvent.set()
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.ctrl:
        print('{0} stop'.format(key))
        recordingEvent.clear()
        keyboard.Listener.stop
        return False

def do_recording():
    while (not exitEvent.is_set()):
        if (recordingEvent.wait(0.1)):
            try:
                data = stream.read(CHUNK)
                # print len(data)
                frames.append(data)
            except IOError:
                print 'warning: dropped frame' # can replace with 'pass' if no message desired

class myRecorder(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        do_recording()

# start recorder thread
recordingThread = myRecorder()
recordingThread.start()

# monitor keyboard
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

# stop recorder thread
exitEvent.set()
recordingThread.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

NB I used the Ctrl key instead of the Cmd key, as it suited my machine better. Hope this is useful.


问:
How can I set items(textbox, img...) on the second (window2) window?
I have a mainwindow, and when it starts, i want to open another one, and put something on it. how it is possible if i declare the second window  like that: </p>

```<code>public MainWindow()
{
    Window Window2 = new Window();
    Window2.Show();
    InitializeComponent();
}
</code>```

答:
You can set the Content property of the new window to anything you want, for example a UserControl that you have created using the Project->Add menu in Visual Studio:

```<code>public MainWindow()
{
    InitializeComponent();

    Window win = new Window() { Width = 100, Height = 100 };
    win.Content = new UserControl1();
    win.Show();
}
</code>```

Body:
I have a mainwindow, and when it starts, i want to open another one, and put something on it. how it is possible if i declare the second window  like that:

public MainWindow()
{
    Window Window2 = new Window();
    Window2.Show();
    InitializeComponent();
}

Body:
You can set the Content property of the new window to anything you want, for example a UserControl that you have created using the Project->Add menu in Visual Studio:

public MainWindow()
{
    InitializeComponent();

    Window win = new Window() { Width = 100, Height = 100 };
    win.Content = new UserControl1();
    win.Show();
}


问:
Changing SelectedItem property of a ListView programatically
I have a 2 ListViews with same items in both of them. What I want to do is that when a selection is made in one ListView, the same selection should be reflected in the other ListView also. The two ListViews are bound to two different ViewModels but both the ViewModels implement the same interface.
I've overridden the Equals methods in both ViewModels.

The two ListViews are on different XAML pages. The first ListView say LV1 is in Page1.xaml and LV2 is in Page2.xaml. What I want is that when I am changing the selection in LV2 the selection in LV1 should also change( one way only ). I've set x:FieldModifier="public" on LV1 and exposing through a static property of Page1 like this:

```<code>public sealed partial class Page1 : Page
{
    public static Page1 page1 { get; private set; }
}
</code>```

And on Page2, I have this :

```<code>private async void LV2_ItemClick(object sender, ItemClickEventArgs e)
{
    var selected = e.ClickedItem as ISomeCommonInterface;
    //Comparision is successful --> Contains() always returns corect value;
    if (Page1.page1.LV1.Items.ToList().Contains(selected))
    {
        Page1.page1.LV1.SelectedItem = null; // this works
        Page1.page1.LV1.SelectedItem = selected; // this doesn't work
    }
}
</code>```

I've found that inside the if condition, assignment to null changes the SelectedItem of LV1 to null but the next line doesn't change it to selected ( it remains null ).

答:
This works for me:

```<code>private void LV1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var selected = (sender as ListView).SelectedItem as string;
    int index = -1;
    for (int i = 0; i < LV2.Items.Count(); i++)
    {
        if (LV2.Items[i] as string == selected){
            index = i;
            break;
        }
    }

    // The if becomes obsolete here, it could be replaced by
    // if(index >= 0)
    if (LV2.Items.ToList().Contains(selected))
    {
        LV2.SelectedIndex = index;
    }
}
</code>```

There is probably an easier way of getting the index of LV1's SelectedItem in LV2, but it should be enough to get you on the right track.

You can check out the minimal testing app I created that shows that SelectedItem works too.

Body:
I have a 2 ListViews with same items in both of them. What I want to do is that when a selection is made in one ListView, the same selection should be reflected in the other ListView also. The two ListViews are bound to two different ViewModels but both the ViewModels implement the same interface.
I've overridden the Equals methods in both ViewModels.

The two ListViews are on different XAML pages. The first ListView say LV1 is in Page1.xaml and LV2 is in Page2.xaml. What I want is that when I am changing the selection in LV2 the selection in LV1 should also change( one way only ). I've set x:FieldModifier="public" on LV1 and exposing through a static property of Page1 like this:

public sealed partial class Page1 : Page
{
    public static Page1 page1 { get; private set; }
}

And on Page2, I have this :

private async void LV2_ItemClick(object sender, ItemClickEventArgs e)
{
    var selected = e.ClickedItem as ISomeCommonInterface;
    //Comparision is successful --> Contains() always returns corect value;
    if (Page1.page1.LV1.Items.ToList().Contains(selected))
    {
        Page1.page1.LV1.SelectedItem = null; // this works
        Page1.page1.LV1.SelectedItem = selected; // this doesn't work
    }
}

I've found that inside the if condition, assignment to null changes the SelectedItem of LV1 to null but the next line doesn't change it to selected ( it remains null ).

Body:
This works for me:

private void LV1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var selected = (sender as ListView).SelectedItem as string;
    int index = -1;
    for (int i = 0; i < LV2.Items.Count(); i++)
    {
        if (LV2.Items[i] as string == selected){
            index = i;
            break;
        }
    }

    // The if becomes obsolete here, it could be replaced by
    // if(index >= 0)
    if (LV2.Items.ToList().Contains(selected))
    {
        LV2.SelectedIndex = index;
    }
}

There is probably an easier way of getting the index of LV1's SelectedItem in LV2, but it should be enough to get you on the right track.

You can check out the minimal testing app I created that shows that SelectedItem works too.


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答: As tvanfosson mentioned, there very useful for mocking, also if you writing a library that depends on outside configuration you can make an IFooProvider and have the calling program implement it.</p>

OwnerDisplayName: koldfyre

Title: Interesting Applications of Interfaces


问:
Bind textbox to float value. Unable to input dot / comma
When I try to input a DOT or a COMMA in a textbox, for example 1.02 or 83,33 the textbox prevents me to input such a value (and the input turns red). The textbox is bound to a float property. Why?

I have bound a textbox to a float Property Power of a class implementing INotifyPropertyChanged.

```<code>private float _power;

public float Power
{
    get { return _power; }
    set
    {
        _power = value;
        OnPropertyChanged("Power");
    }
}
</code>```

In Xaml

```<code><TextBox Name="txtPower" Height="23" TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</code>```

I have no custom validation at all right now.

Also tried decimal but it does not work either. For string everything works fine.

答:
to fix dot and comma issue in textbox binding to decimal or float </p>

```<code>1-  UpdateSourceTrigger = LostFocus
2-  add string format StringFormat={}{0:#.##} to escape unneeded zeros

<TextBox Name="txtPower" Height="23"
         TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay,
         UpdateSourceTrigger=LostFocus ,StringFormat={}{0:#.##}}"></TextBox>
</code>```

Body:
When I try to input a DOT or a COMMA in a textbox, for example 1.02 or 83,33 the textbox prevents me to input such a value (and the input turns red). The textbox is bound to a float property. Why?

I have bound a textbox to a float Property Power of a class implementing INotifyPropertyChanged.

private float _power;

public float Power
{
    get { return _power; }
    set
    {
        _power = value;
        OnPropertyChanged("Power");
    }
}

In Xaml

<TextBox Name="txtPower" Height="23" TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>

I have no custom validation at all right now.

Also tried decimal but it does not work either. For string everything works fine.

Body:
to fix dot and comma issue in textbox binding to decimal or float

1-  UpdateSourceTrigger = LostFocus
2-  add string format StringFormat={}{0:#.##} to escape unneeded zeros

<TextBox Name="txtPower" Height="23"
         TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay,
         UpdateSourceTrigger=LostFocus ,StringFormat={}{0:#.##}}"></TextBox>


问:
How can i get the logs of past months in postgres DB .
Issue :

Someone has added a junk column in one of my table.I want to figure it out from the logs as when and from where this activity has been performed.

Please Help regarding this issue.

答:
Make sure enable logging in postgresql.conf

```<code>1.log_destination = 'stderr' #log_destination = 'stderr,csvlog,syslog'
2.logging_collector = on     #need restart
3.log_directory = 'pg_log'
4.log_file_name = 'postgresql-%Y-%m-%d_%H%M%S.log'
5.log_rotation_age = 1d
6.log_rotation_size = 10MB
7.log_min_error_statement = error
8.log_min_duration_statement = 5000 # -1 = disable ; 0 = ALL ; 5000 = 5sec
9.log_line_prefix = '|%m|%r|%d|%u|%e|'
10.log_statment = 'ddl' # 'none' | 'ddl' | 'mod' | 'all'
#prefer 'ddl' because the log output will be 'ddl' and 'query min duration'
</code>```

If you don't enable it, make sure enable it now.

if you don't have log the last attempt is pg_xlogdump your xlog file under pg_xlog and look for DDL

Body:
Make sure enable logging in postgresql.conf

1.log_destination = 'stderr' #log_destination = 'stderr,csvlog,syslog'
2.logging_collector = on     #need restart
3.log_directory = 'pg_log'
4.log_file_name = 'postgresql-%Y-%m-%d_%H%M%S.log'
5.log_rotation_age = 1d
6.log_rotation_size = 10MB
7.log_min_error_statement = error
8.log_min_duration_statement = 5000 # -1 = disable ; 0 = ALL ; 5000 = 5sec
9.log_line_prefix = '|%m|%r|%d|%u|%e|'
10.log_statment = 'ddl' # 'none' | 'ddl' | 'mod' | 'all'
#prefer 'ddl' because the log output will be 'ddl' and 'query min duration'

If you don't enable it, make sure enable it now.

if you don't have log the last attempt is pg_xlogdump your xlog file under pg_xlog and look for DDL


问:
phpMyAdmin can't connect to remote sever on Windows 7 from Linux client
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

```<code>$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;
</code>```

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

```<code>PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)
</code>```

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin

答:
I've resolved in this way:
put the setting lines after $GLOBALS['server'] = 0; with the variable i initialized to 1 ( $i=1; ) instead of put them at the bottom of common.inc.php.

Body:
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin


问:
React-native link is not working properly
I tried installing and linking react-native sound into my project. However, when I run the following command in my project directory,

```<code>react-native link react-native-sound
</code>```

the library doesn't link and I get the following result:

```<code>Scanning 758 folders for symlinks in /Users/MY_USER_NAME/PROJECT_NAME/node_modules
</code>```

I think my node or npm setup is wrong.

答:
Ok after some digging, I found the issue.
https://github.com/facebook/react-native/pull/14863

Maybe try applying that fix locally, it should work then.

Body:
I tried installing and linking react-native sound into my project. However, when I run the following command in my project directory,

react-native link react-native-sound

the library doesn't link and I get the following result:

Scanning 758 folders for symlinks in /Users/MY_USER_NAME/PROJECT_NAME/node_modules

I think my node or npm setup is wrong.


问:
JMeter can I run it locally?
In my opinion, load tests should be performed from several different IP addresses simultaneously(because of restrictions on http). Am I right?

I will do load tests for:
Number of Threads (users):  2000
Ramp-Up Period (in seconds): 10

答:
To perform load test in serveral different IP address use Jmeter remote test</p>

```<code>control multiple, remote JMeter engines from a single JMeter client. By running JMeter remotely, you can replicate a test across many low-end computers and thus simulate a larger load on the server.
</code>```

Title: JMeter can I run it locally?

Body:
To perform load test in serveral different IP address use Jmeter remote test

control multiple, remote JMeter engines from a single JMeter client. By running JMeter remotely, you can replicate a test across many low-end computers and thus simulate a larger load on the server.


问:
How to do "go get" on a specific tag of a github repository
I am trying to compile the InfluxDB database (version v0.8.8) using go get github.com/influxdb/influxdb

But this pulls the master branch, and I need the v0.8.8 tag.

I have tried to do:  go get github.com/influxdb/influxdb/releases/tag/v0.8.8 but this fails saying unable to find.

I also tried to do a regular go get of the master branch, and then manually checking out the tag using git in GOPATH/src/github... in order to set the corret version.

The problem using the last approach is that when I try to pull the dependencies with go get -u -f ./... it tries to find them in the master branch, and some of them do not exist on the master branch...

TL;DR: perform go get on a specific github tag, and pull the correct dependencies.

答: maven golang plugin allows to play with branch, tag and revision during GET, you can take a look at its test for such cases with GIT repository</p>


问:
Change Enter from submission to Tab?
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

```<code>e.returnValue = false;
e.cancel = true;
</code>```

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

答:
This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:

Here's a simple example:

```<code>$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).next("input").focus();
    }
});
</code>```

Example: http://jsfiddle.net/andrewwhitaker/Txg65/

Update: If you have elements in between your inputs, using plain next() will not work.  Instead, use nextAll():

```<code>$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).nextAll("input").eq(0).focus();
    }
});
</code>```

http://jsfiddle.net/andrewwhitaker/GRtQY/

Title: Change Enter from submission to Tab?

Body:
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

e.returnValue = false;
e.cancel = true;

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

Body:
This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:

Here's a simple example:

$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).next("input").focus();
    }
});

Example: http://jsfiddle.net/andrewwhitaker/Txg65/

Update: If you have elements in between your inputs, using plain next() will not work.  Instead, use nextAll():

$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).nextAll("input").eq(0).focus();
    }
});

http://jsfiddle.net/andrewwhitaker/GRtQY/


问:
VBA to cut, delete and move a row to another worksheet based on cell value using command button
I have been working on a vba which will automatically move an entire row from the Mailing Log worksheet to the Completed Log worksheet if the values "Complete" or "Closed Incomplete" are entered into Column H using a command button in the header of Column H.

The command button is working, but for some strange reason when it pastes the row into the completed log, instead of pasting it onto the next available line, it pastes it right at the bottom of the sheet in row "1048542". also I have only managed to get it working for the value 'Complete' and not yet for Closed Incomplete.

Can someone please help?

I have attached an example of my spreadsheets and my current VBA code Is as below:

```<code>Private Sub CommandButton1_Click()

Dim Check As Range, r As Long, lastrow2 As Long, lastrow As Long
    Application.ScreenUpdating = False
        lastrow = Worksheets("Mailing LOG").UsedRange.Rows.Count
            lastrow2 = Worksheets("Completed Log").UsedRange.Rows.Count
                If lastrow2 = 1 Then lastrow2 = 0
                    For r = lastrow To 2 Step -1
                        If Range("H" & r).Value = "Complete" Then
                            Rows(r).Cut Destination:=Worksheets("Completed Log").Range("A" & lastrow2 + 1)
            lastrow2 = lastrow2 + 1
            Else:
        End If
    Next r
Application.ScreenUpdating = True
End Sub
</code>```

Spreadsheet

答:
Try this instead. UsedRange doesn't always work as expected as it can include cells previously formatted. I have also added some sheet references to your code to increase clarity (and ensure your code works as expected whichever sheet is active at the time).</p>

```<code>Private Sub CommandButton1_Click()

Dim Check As Range, r As Long, lastrow2 As Long, lastrow As Long

Application.ScreenUpdating = False

lastrow = Worksheets("Mailing LOG").UsedRange.Rows.Count

For r = lastrow To 2 Step -1
    If Worksheets("Mailing LOG").Range("H" & r).Value = "Complete" Then
        Worksheets("Mailing LOG").Rows(r).Cut Destination:=Worksheets("Completed Log").Range("A" & Rows.Count).End(xlUp)(2)
    End If
Next r

Application.ScreenUpdating = True

End Sub
</code>```

Body:
I have been working on a vba which will automatically move an entire row from the Mailing Log worksheet to the Completed Log worksheet if the values "Complete" or "Closed Incomplete" are entered into Column H using a command button in the header of Column H.

The command button is working, but for some strange reason when it pastes the row into the completed log, instead of pasting it onto the next available line, it pastes it right at the bottom of the sheet in row "1048542". also I have only managed to get it working for the value 'Complete' and not yet for Closed Incomplete.

Can someone please help?

I have attached an example of my spreadsheets and my current VBA code Is as below:

Private Sub CommandButton1_Click()

Dim Check As Range, r As Long, lastrow2 As Long, lastrow As Long
    Application.ScreenUpdating = False
        lastrow = Worksheets("Mailing LOG").UsedRange.Rows.Count
            lastrow2 = Worksheets("Completed Log").UsedRange.Rows.Count
                If lastrow2 = 1 Then lastrow2 = 0
                    For r = lastrow To 2 Step -1
                        If Range("H" & r).Value = "Complete" Then
                            Rows(r).Cut Destination:=Worksheets("Completed Log").Range("A" & lastrow2 + 1)
            lastrow2 = lastrow2 + 1
            Else:
        End If
    Next r
Application.ScreenUpdating = True
End Sub

Spreadsheet

Body:
Try this instead. UsedRange doesn't always work as expected as it can include cells previously formatted. I have also added some sheet references to your code to increase clarity (and ensure your code works as expected whichever sheet is active at the time).

Private Sub CommandButton1_Click()

Dim Check As Range, r As Long, lastrow2 As Long, lastrow As Long

Application.ScreenUpdating = False

lastrow = Worksheets("Mailing LOG").UsedRange.Rows.Count

For r = lastrow To 2 Step -1
    If Worksheets("Mailing LOG").Range("H" & r).Value = "Complete" Then
        Worksheets("Mailing LOG").Rows(r).Cut Destination:=Worksheets("Completed Log").Range("A" & Rows.Count).End(xlUp)(2)
    End If
Next r

Application.ScreenUpdating = True

End Sub


问:
Where to put Entity Framework Data Model in MVC application?
Lets consider default ASP.NET MVC application folder structure, so it's looks like this:

```<code>-App_data
-Content
-Controllers
    HomeController.cs
-Models
    AccountModels.cs
-Scripts
-Views
</code>```

My question is: Where is the best place to put Entity Framework Data Model (EDMX) file? Is it Models folder? Yes - we know that good solution is to introduce new Project and reference it to MVC application, but lets forget about this now.

答:
I would put the EF-model (aka physical model) always in its own assembly or in a "core" assembly outside of main MVC application. The same applies for your business-logic / domain-logic / domain-services / etc. Separate the non-web stuff from the MVC-Web-Application.

This will help you re-use the core part of your app. For example when you need to expose it as a service, a command-line tool, migration-tool, etc.

Because storing this in its own assembly is so easy and takes you a few minutes I highly recommend doing this for each and every tiny app too.

Body:
Lets consider default ASP.NET MVC application folder structure, so it's looks like this:

-App_data
-Content
-Controllers
    HomeController.cs
-Models
    AccountModels.cs
-Scripts
-Views

My question is: Where is the best place to put Entity Framework Data Model (EDMX) file? Is it Models folder? Yes - we know that good solution is to introduce new Project and reference it to MVC application, but lets forget about this now.


问:
Copy content from one field to another
I’m looking for a SQL query script:

```<code>COPY ContactName, City
    WHERE CustomerID (A)
TO ContactName, City
   WHERE CustomerID (B)
</code>```

I know this isn’t right, but I hope you understand what I mean.

Regards!

答:
```<code>UPDATE Customers
SET ContactName = (SELECT ContactName WHERE CustomerID ='A'), City = (SELECT City WHERE CustomerID ='A')
WHERE CustomerID=B
</code>```

This should work

Title: Copy content from one field to another

Body:
I’m looking for a SQL query script:

COPY ContactName, City
    WHERE CustomerID (A)
TO ContactName, City
   WHERE CustomerID (B)

I know this isn’t right, but I hope you understand what I mean.

Regards!

Body:
UPDATE Customers
SET ContactName = (SELECT ContactName WHERE CustomerID ='A'), City = (SELECT City WHERE CustomerID ='A')
WHERE CustomerID=B

This should work


问:
How do I restrict an android app to be available on only devices that accept a sim card?
I'm working on an app that uses a feature that is only available if the device can receive a text message. How can I ensure that the app is only compatible with sim-card acceptable devices?</p>

答:
You should use a flag in the AndroidManifest.xml

Add the uses-feature line to your manifest in this way:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="your.package.app">

    <!-- Add this line to your manifest -->
    <uses-feature android:name="android.hardware.telephony" android:required="true" />

    <!-- other declarations -->
    [....]

</manifest>
</code>```

In this way Google Play Store should not list your app for devices which doesn't have a SIM or radio communications.

More info here in the Telephony hardware features section

Body:
You should use a flag in the AndroidManifest.xml

Add the uses-feature line to your manifest in this way:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="your.package.app">

    <!-- Add this line to your manifest -->
    <uses-feature android:name="android.hardware.telephony" android:required="true" />

    <!-- other declarations -->
    [....]

</manifest>

In this way Google Play Store should not list your app for devices which doesn't have a SIM or radio communications.

More info here in the Telephony hardware features section


问:
PHP Constants Containing Arrays?
This failed:

```<code> define('DEFAULT_ROLES', array('guy', 'development team'));
</code>```

Apparently, constants can't hold arrays. What is the best way to get around this?

```<code>define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);
</code>```

This seems like unnecessary effort.

答:
PHP 7+

As of PHP 7, you can just use the define() function to define a constant array :

```<code>define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"
</code>```

Title: PHP Constants Containing Arrays?

Body:
This failed:

 define('DEFAULT_ROLES', array('guy', 'development team'));

Apparently, constants can't hold arrays. What is the best way to get around this?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);

This seems like unnecessary effort.

Body:
PHP 7+

As of PHP 7, you can just use the define() function to define a constant array :

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"


问:
FULL OUTER JOIN throwing error "wrap select in parentheses"
I am having trouble with a part of my SQL call, I receive this error

 Error: Syntax error: Each subquery argument for table-valued function calls must be enclosed in parentheses. To fix this, replace SELECT... with (SELECT...) at [32:5]

This is at the SELECT after the FULL OUTER JOIN EACH, I'd argue that I have done that, I do not know what is wrong here so any suggestions would be much appriciated.

I am trying to create a funnel that more acurately sorts previous customers from new. There are in total 3 levels in the funnel, for "simplicity" I'll only show two.

```<code>SELECT
 COUNT(s0.firstHit) AS pageId1,
 SUM(s0.exit) AS pageId2,
 COUNT(s1.firstHit) AS pageId3,
 SUM(s1.exit) AS pageId4
FROM(
  SELECT
    s0.fullVisitorId,
    s0.visitId,
    s0.firstHit,
    s0.exit,
    s1.firstHit,
    s1.exit
  FROM (
    SELECT
      fullvisitorid,
      visitid,
      (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstHit,
      (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS exitFlag
    FROM
      `<ID>.ga_sessions_2017*`
    WHERE
      _TABLE_SUFFIX BETWEEN '0601' AND '0602'
      AND 1 = 1
      AND EXISTS(SELECT 1 FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId'))
  AND EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE (SELECT COUNT(value) FROM UNNEST(hits.customDimensions) custd WHERE index=20) > 0)
  AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s0
  FULL OUTER JOIN EACH(
  SELECT
    fullVisitorId,
    visitId,
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s1
ON
  s0.fullVisitorId = s1.fullVisitorId
  AND s0.visitId = s1.visitId ) s01
</code>```

答:
In the last subquery:

```<code>  SELECT
    fullVisitorId,
    visitId
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId
</code>```

it looks to me like you need a comma after visitId in the third line.

Best of luck.

Body:
I am having trouble with a part of my SQL call, I receive this error

 Error: Syntax error: Each subquery argument for table-valued function calls must be enclosed in parentheses. To fix this, replace SELECT... with (SELECT...) at [32:5]

This is at the SELECT after the FULL OUTER JOIN EACH, I'd argue that I have done that, I do not know what is wrong here so any suggestions would be much appriciated.

I am trying to create a funnel that more acurately sorts previous customers from new. There are in total 3 levels in the funnel, for "simplicity" I'll only show two.

SELECT
 COUNT(s0.firstHit) AS pageId1,
 SUM(s0.exit) AS pageId2,
 COUNT(s1.firstHit) AS pageId3,
 SUM(s1.exit) AS pageId4
FROM(
  SELECT
    s0.fullVisitorId,
    s0.visitId,
    s0.firstHit,
    s0.exit,
    s1.firstHit,
    s1.exit
  FROM (
    SELECT
      fullvisitorid,
      visitid,
      (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstHit,
      (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS exitFlag
    FROM
      `<ID>.ga_sessions_2017*`
    WHERE
      _TABLE_SUFFIX BETWEEN '0601' AND '0602'
      AND 1 = 1
      AND EXISTS(SELECT 1 FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId'))
  AND EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE (SELECT COUNT(value) FROM UNNEST(hits.customDimensions) custd WHERE index=20) > 0)
  AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s0
  FULL OUTER JOIN EACH(
  SELECT
    fullVisitorId,
    visitId,
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s1
ON
  s0.fullVisitorId = s1.fullVisitorId
  AND s0.visitId = s1.visitId ) s01

Body:
In the last subquery:

  SELECT
    fullVisitorId,
    visitId
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId

it looks to me like you need a comma after visitId in the third line.

Best of luck.


问:
Binary coded decimal (BCD) to Hexadecimal conversion
can someone explain to me how to convert BCD to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal.
Thanks.</p>

答: BCD is a subset of hexadecimal, so there is no conversion necessary -- any given BCD value is identical to the corresponding hexadecimal value.  For example, '98' in BCD is 10011000, which is the same as 98 in hexadecimal</p>


问:
How do I set the IP Address of a device using Windows Universal App?
I have a Raspberry Pi 2 with Windows 10 ioT installed.  How do I set the IP Address statically in code? </p>

答: Now it can be done directly with Windows Device Portal (with your browser)


问:
Can't start Chrome Driver with saved profile on Selenium with C#
I wrote a method to start clear Chrome Driver with different parameters, and it works. But when I was needed to start Chrome with my default profile (with saved cookies) - I wrote this lines of code, it runs browser (and I see my bookmarks, so it runs with cookies), but visual studio sleeps for a minute at return line, and throw me an exception. What is the problem here?

```<code>public RemoteWebDriver SetDriver(String Browser)
    {
        switch (Browser)
        {
            case "CH":
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("--user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data");
                return new ChromeDriver(options);
</code>```

```<code>OpenQA.Selenium.WebDriverException was unhandled
HResult=-2146233088
Message=The HTTP request to the remote WebDriver server for URL http://localhost:52036/session timed out after 60 seconds.
Source=WebDriver
StackTrace:
w OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 170
w OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 121
w OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\DriverServiceCommandExecutor.cs:wiersz 84
w OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 1177
w OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 1114
w OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 141
w OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeOptions options) w c:\Projects\webdriver\dotnet\src\webdriver\Chrome\ChromeDriver.cs:wiersz 76
w AutoLike.Login.SetDriver(String Browser) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Login.cs:wiersz 70
w AutoLike.Login..ctor(String Browser, String URL, String DownloadPath) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Login.cs:wiersz 32
w AutoLike.Form1.button1_Click(Object sender, EventArgs e) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Form1.cs:wiersz 34
w System.Windows.Forms.Control.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
w System.Windows.Forms.Control.WndProc(Message& m)
w System.Windows.Forms.ButtonBase.WndProc(Message& m)
w System.Windows.Forms.Button.WndProc(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.Run(Form mainForm)
w AutoLike.Program.Main() w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Program.cs:wiersz 19
w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
w System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233079
Message=Upłynął limit czasu operacji
Source=System
StackTrace:
w System.Net.HttpWebRequest.GetResponse()
w OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 162
</code>```

答:
You need to quote the path since it contains a space character:</p>

```<code>options.AddArguments(String.Format(
   "--user-data-dir=\"{0}\"", @"C:\Users\user\AppData\Local\Google\Chrome\User Data"));
</code>```

Body:
I wrote a method to start clear Chrome Driver with different parameters, and it works. But when I was needed to start Chrome with my default profile (with saved cookies) - I wrote this lines of code, it runs browser (and I see my bookmarks, so it runs with cookies), but visual studio sleeps for a minute at return line, and throw me an exception. What is the problem here?

public RemoteWebDriver SetDriver(String Browser)
    {
        switch (Browser)
        {
            case "CH":
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("--user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data");
                return new ChromeDriver(options);

OpenQA.Selenium.WebDriverException was unhandled
HResult=-2146233088
Message=The HTTP request to the remote WebDriver server for URL http://localhost:52036/session timed out after 60 seconds.
Source=WebDriver
StackTrace:
w OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 170
w OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 121
w OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\DriverServiceCommandExecutor.cs:wiersz 84
w OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 1177
w OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 1114
w OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:wiersz 141
w OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeOptions options) w c:\Projects\webdriver\dotnet\src\webdriver\Chrome\ChromeDriver.cs:wiersz 76
w AutoLike.Login.SetDriver(String Browser) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Login.cs:wiersz 70
w AutoLike.Login..ctor(String Browser, String URL, String DownloadPath) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Login.cs:wiersz 32
w AutoLike.Form1.button1_Click(Object sender, EventArgs e) w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Form1.cs:wiersz 34
w System.Windows.Forms.Control.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
w System.Windows.Forms.Control.WndProc(Message& m)
w System.Windows.Forms.ButtonBase.WndProc(Message& m)
w System.Windows.Forms.Button.WndProc(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.Run(Form mainForm)
w AutoLike.Program.Main() w d:\users\documents\visual studio 2015\Projects\AutoLike\AutoLike\Program.cs:wiersz 19
w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
w System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233079
Message=Upłynął limit czasu operacji
Source=System
StackTrace:
w System.Net.HttpWebRequest.GetResponse()
w OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request) w c:\Projects\webdriver\dotnet\src\webdriver\Remote\HttpCommandExecutor.cs:wiersz 162

Body:
You need to quote the path since it contains a space character:

options.AddArguments(String.Format(
   "--user-data-dir=\"{0}\"", @"C:\Users\user\AppData\Local\Google\Chrome\User Data"));


问:
Regular Expressions: AND behavior
I'm studying regular expressions in Javascript

I've seen many ways to do exclusive matching through the OR operator with [] and | within groups ().

I can't understand how to achieve the AND behavior with regular expressions. I've done some research but I didn't find what I need.

Here an example. I have the following string: kata. I want to compare it with another string: steak.
 The goal is to return true if all the letters in steak is contained in kata. If I use this regular expression [steak] it returns true but actually it should return false because in kata there is no "s".

Example 2. String1 = scriptsjava, string2 = javascript, result = true (because string2 is contained in string1)

Example 3. String1 = jscripts, string2 = javascript, result = false (because string2 is not fully contained in string1)

Example 4. String1 = rkqodlw, string2 = world, result = true (because the string world is in the first string)

I thought that using regular expressions is the best way and I considered string2 as a pattern. My solution to this problem is the following

```<code> var validate=true;
 var counter = 0;
 str2.split("").map(val => {
   counter++;
    var char = new RegExp(val);

    if (char.test(str1) === false) { validate = false;} else
    {
    str1 = str1.slice(0, counter+1) + str1.slice(counter+1,str1.length);
    console.log(str1);
    }

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

I think is not the most efficient though. Do you have a better solution for this?

答:
You want a set comparison, specifically a superset check. Simple with a Set:

let s1 = 'javascript';
let s2 = 'scriptsjava';

Set.prototype.isSuperset = function(subset) {
    for (var elem of subset) {
        if (!this.has(elem)) {
            return false;
        }
    }
    return true;
}

console.log(new Set(s1).isSuperset(new Set(s2)));```

Title: Regular Expressions: AND behavior

Body:
I'm studying regular expressions in Javascript

I've seen many ways to do exclusive matching through the OR operator with [] and | within groups ().

I can't understand how to achieve the AND behavior with regular expressions. I've done some research but I didn't find what I need.

Here an example. I have the following string: kata. I want to compare it with another string: steak.
 The goal is to return true if all the letters in steak is contained in kata. If I use this regular expression [steak] it returns true but actually it should return false because in kata there is no "s".

Example 2. String1 = scriptsjava, string2 = javascript, result = true (because string2 is contained in string1)

Example 3. String1 = jscripts, string2 = javascript, result = false (because string2 is not fully contained in string1)

Example 4. String1 = rkqodlw, string2 = world, result = true (because the string world is in the first string)

I thought that using regular expressions is the best way and I considered string2 as a pattern. My solution to this problem is the following

 var validate=true;
 var counter = 0;
 str2.split("").map(val => {
   counter++;
    var char = new RegExp(val);

    if (char.test(str1) === false) { validate = false;} else
    {
    str1 = str1.slice(0, counter+1) + str1.slice(counter+1,str1.length);
    console.log(str1);
    }

 });
 return validate;

I think is not the most efficient though. Do you have a better solution for this?


问:
Using Do/Catch in Swift
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

```<code>func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}
</code>```

It would be very nice if somebody could help me.

答:
Those answer were written till mine are right. There is one way: with handler check get result and use by your point.</p>

```<code>enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?, completionHandler: @escaping (_ result: String? , _ error: Error?) -> Void ) {

  guard let data = data else {
    // Data is missing
    throw nil, Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result, nil
}

// example of calling this function
process(data: "A data to process"){(result, error) -> Void in
     //do any stuff
     /*if error == nil {
     }*/
}
</code>```

Title: Using Do/Catch in Swift

Body:
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}

It would be very nice if somebody could help me.

Body:
Those answer were written till mine are right. There is one way: with handler check get result and use by your point.

enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?, completionHandler: @escaping (_ result: String? , _ error: Error?) -> Void ) {

  guard let data = data else {
    // Data is missing
    throw nil, Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result, nil
}

// example of calling this function
process(data: "A data to process"){(result, error) -> Void in
     //do any stuff
     /*if error == nil {
     }*/
}


问:
Multiple number from EditText with assigned number Android
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

```<code>public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}
</code>```

答:
It works now... on the existing code I've added this code

```<code>@Override
public void onClick(View v) {
    calculate();
}
</code>```

Thanks anyway :)

Body:
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}

Body:
It works now... on the existing code I've added this code

@Override
public void onClick(View v) {
    calculate();
}

Thanks anyway :)


问:
URL redirect based on date and time
I want to redirect to an external dynamic url, one which contains today’s month, date, day, hour. E.g. http://url.com/20170706-2200-048.mp3

I read that using the .htaccess file and mod_rewrite I could use something like http://url.com/news/%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}-%{TIME_HOUR}-048.mp3.

How would I set this up in htaccess? And is there a way I could set a custom timezone? I.e. to EST or NZT.

答:
There have two variants.

First one is:

```<code>php_value date.timezone 'Region/Zone'
</code>```

The second one is:

```<code>SetEnv TZ America/Washington
</code>```

And you can use the time for redirect something like this:

```<code>RewriteRule ^$ /news/%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}-%{TIME_HOUR}.mp3 [R=301,L]
</code>```

I did not test it and am not sure it works.

Title: URL redirect based on date and time

Body:
There have two variants.

First one is:

php_value date.timezone 'Region/Zone'

The second one is:

SetEnv TZ America/Washington

And you can use the time for redirect something like this:

RewriteRule ^$ /news/%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}-%{TIME_HOUR}.mp3 [R=301,L]

I did not test it and am not sure it works.

ContentLicense: CC BY-SA 4.0


答: There is no EACH keyword when using standard SQL; this is specific to legacy SQL. Remove that word and your query will probably work.

Title: FULL OUTER JOIN throwing error "wrap select in parentheses"


问:
Range of values for GetMaxAmplitude
I've got an interesting idea for an outside of the box use of the mic port on an android phone.  I'm brainstorming ways to use an android phone to log roast temperatures inside my coffee roaster.  The thought popped into my head.  A microphone is a low-voltage and so is my thermocouple.  So I started looking through the android methods to see if there was anything that might allow me to get the actual millivolt reading from the port.  The GetMaxAmplitude function is the only thing I found.  Does anyone know the range of values that are returned by the GetMaxAmplitude function?

If you know that this will not work, just let me know.

Thanks in advance,

答:
Well, I myself have been working to find the absolute rang of values that come from the getMaxAmplitude() function, but I haven't been able to find any exact answers. There was one thread that said that voices can return anything from 0 to 25000. I do know that the minimum value is 0. Also, it returns an Integer, which can only contain whole numbers, so I don't think that it is actually returning the raw millivolt reading, since that would typically contain decimals, too.

Very interesting idea though!!

maybe something here will help:

 Microphone input

EDIT:

I have discovered the max value! it is 32767, which is the max for a signed 16-bit integer. The minimum value is of course, 0, because you can't have less than no sound. This also supports the theory that getMaxAmplitude() doesn't return the actual millivolt value, because getting 32.8 volts out of a microphone...isn't going to happen.

Title: Range of values for GetMaxAmplitude


问:
Getting instagram post url from media id
I have the post media_id in my hands and I'd like to know if there is a way to create a valid url from it.

For instance, if you have a Facebook post id (xxxx_yyyy) on your hands, you can create the following url from it (http://facebook.com/xxxx/posts/yyyy) and directly access the original post.

Is there a way to do this on Instagram? Having media_id (and user_id) in my hands, is it possible to create a single post url?

答:
Here's how to derive the URL segment from the media ID using JavaScript:

```<code>function getInstagramUrlFromMediaId(media_id) {
    media_id = parseInt(media_id.substring(0, media_id.indexOf('_')));
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    var shortenedId = '';
    while (media_id > 0) {
        var remainder = modulo(media_id % 64);
        media_id = (media_id - remainder) / 64;
        shortenedId = alphabet.charAt(remainder) + shortenedId;
    }
    return 'https://www.instagram.com/p/' + shortenedId + '/';
}
</code>```

Depending on how old the Instagram post is, you may need to use a library like BigInteger to handle the larger IDs.

You can find a breakdown of the encoding between media id and url segment here: http://carrot.is/coding/instagram-ids

Body:
Here's how to derive the URL segment from the media ID using JavaScript:

function getInstagramUrlFromMediaId(media_id) {
    media_id = parseInt(media_id.substring(0, media_id.indexOf('_')));
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    var shortenedId = '';
    while (media_id > 0) {
        var remainder = modulo(media_id % 64);
        media_id = (media_id - remainder) / 64;
        shortenedId = alphabet.charAt(remainder) + shortenedId;
    }
    return 'https://www.instagram.com/p/' + shortenedId + '/';
}

Depending on how old the Instagram post is, you may need to use a library like BigInteger to handle the larger IDs.

You can find a breakdown of the encoding between media id and url segment here: http://carrot.is/coding/instagram-ids


问:
How to explain the code output of this multi-threading program in Java?
I am studying multi-threading in java and wrote the following code.

```<code>    public class MulThread extends Thread
{
    public void run()
    {
        for(int i=1; i<5;i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(Exception e){ System.out.println(e);}
            System.out.println(i);
        }
    }

public static void main(String [] args)
{
    MulThread t1 = new MulThread();
    MulThread t2 = new MulThread();
    MulThread t3 = new MulThread();

    t1.start();
    t1.run();
    t2.start();
    t2.run();

    t3.start();
    t3.run();

}
}
</code>```

I discussed this with some friends, and I came to the conclusion that the output should be a complete mess. But for some reason, the compiler always produces the following output:

```<code>1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
</code>```

Can someone explain what exactly is happening here when the threads reach the scheduler? Why isn't the output a mess of 1, 2, 3, and 4, each repeated 6 times in a random soup?

A few of my mentors tell me it's just a coincidence, and it depends on my OS or something, but I'm skeptical about that. I've run the code over 10 times, and it always produces the same results.

答:
When you call t1.start(), a secondary thread starts and runs the run() method.
When you call t1.run(), you are executing the run() method on the main thread.

This means that t2.start(); will only be executed after t1.run(); finished the loop, and at this point the thread created by t1.start() has already finished.

Since the loop of the run() method contains a large sleep (half a second), there's a very high probability that the outputs of t1.start() (which runs on a secondary thread) and t1.run() (which runs on the main thread) will be interleaved (since that sleep is enough time for the second thread to get control and print the next output while the first thread is sleeping).

If you reduce the sleep period, you'll probably see different output.

Body:
I am studying multi-threading in java and wrote the following code.

    public class MulThread extends Thread
{
    public void run()
    {
        for(int i=1; i<5;i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(Exception e){ System.out.println(e);}
            System.out.println(i);
        }
    }

public static void main(String [] args)
{
    MulThread t1 = new MulThread();
    MulThread t2 = new MulThread();
    MulThread t3 = new MulThread();

    t1.start();
    t1.run();
    t2.start();
    t2.run();

    t3.start();
    t3.run();

}
}

I discussed this with some friends, and I came to the conclusion that the output should be a complete mess. But for some reason, the compiler always produces the following output:

1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4

Can someone explain what exactly is happening here when the threads reach the scheduler? Why isn't the output a mess of 1, 2, 3, and 4, each repeated 6 times in a random soup?

A few of my mentors tell me it's just a coincidence, and it depends on my OS or something, but I'm skeptical about that. I've run the code over 10 times, and it always produces the same results.


答:
You can use uses-feature flag in the AndroidManifest.xml

```<code><uses-feature android:name="android.hardware.telephony" android:required="true" />
</code>```

By using this it will filter simless devices for you.
https://developer.android.com/guide/topics/manifest/uses-feature-element.html

Title: How do I restrict an android app to be available on only devices that accept a sim card?

Body: I'm working on an app that uses a feature that is only available if the device can receive a text message. How can I ensure that the app is only compatible with sim-card acceptable devices?

Body:
You can use uses-feature flag in the AndroidManifest.xml

<uses-feature android:name="android.hardware.telephony" android:required="true" />

By using this it will filter simless devices for you.
https://developer.android.com/guide/topics/manifest/uses-feature-element.html


问:
aframe environment component with particle system
I was trying to add different particles from particle component in combination with environment component of aframe, i was not able to create a fiddle as at the time of writing this question i was getting 'Not found: package "aframe-environment-component" ' for aframe-environment-component,
 While looking around i found  takahirox, which works well with environment component (tested), but i am trying to put different particle system effect to different environments. I tried to set presets for different particle systems like, rain, snow, etc. But, i was not able to run it successfully with environment-component and particle system component in one page, if i remove environment component, i am able to set particle system properly, but not with environment component. Any help is appreciated.</p>

答:
I am quite unable to figure out why they are not working together, so I can only offer a workaround: You can tweak takahirox component properties to get snow, I've tried setting:

color:#ffffff;vector:-1 -2 0;count:500;opacity: 1;splash:false;width:40;dropHeight:0.2

 White color, slower drop, less drops, no opacity, no splash, no "rainDrop tail", and it quite looks like snow :)

If You want to achieve dust, i would get there a brown fog, and make the rain go more horizontal ( tweak the vector attribute ).


问:
Regexp: only match word if it doesn't start with a dot
Lets say I have this string:

key something.key() (.key)(key)

I would like regex to only match the word "keys" that are inside "[ ]"

[key] something.key() (.key)([key])

I have used this regex currently /(?!\.)key/g

But that only excludes dot and still selects word even if it startet with a dot.

答:
Use negative character class to match not a dot:

[^\.]

Then add ^ to match not a dot or at the beginning of the string:

([^\.]|^)

Add ?: to the group to make it non-capturing.

(?:[^\.]|^)

Finally add a capturing group matching your word:

(?:[^\.]|^)(word)

You could achieve the same result using negative look-behind:

(?<!\.)word

Alas, JavaScript regex doesn’t implement it.


问:
android loading and saving images on the device
I am building the application that will load list of news from the website. Each news/headline has an image. I want to save/cash the images so user does not has to download them again.

Q: In your opinion, what would be a better/more sufficient way: Loading images and saving them on the device or use the CacheManager? At the moment I am using the first solution and everything works fine. However, the website has many categories and even more news per category therefore there are lot of images saved on the device. Is it normal in this type of applications to save the images on the device?

Thanks for your help,
marqs

答: I didn't find a reason to use CacheManager. I used getCacheDir and stored everything on file. I have two levels of cache. First when I fetch it, I store in memory and disk. When in memory gets bigger than 30 objects, I started clearing the memory to make some room for the new images coming. However, I still keep the images around on disk and bring in to memory as needed. I found this to give me the smoothest scrolling. After about an hour, I start expiring the image on disk too. </p>