问:
How to make QTMovie play file from URL with forced (MP3) type?
I'm using QTKit to progressively download and play an MP3 from a URL. According to this documentation, this is the code I should use to accomplish that:

```<code>NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar.mp3"];

NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithURL:mp3URL error:&error];
[sound play];
</code>```

This works, and does exactly what I want — the MP3 URL is lazily downloaded and starts playing immediately. However, if the URL does not have the ".mp3" path extension, it fails:

```<code>NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar"];

NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithURL:mp3URL error:&error];
[sound play];
</code>```

No error is given, no exception is raised; the duration of the sound is just set to zero, and nothing plays.

The only way I have found to work around this is to force a type by loading the data manually and using a QTDataReference:

```<code>NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar"];
NSData *mp3Data = [NSData dataWithContentsOfURL:mp3URL];

QTDataReference *dataReference =
    [QTDataReference dataReferenceWithReferenceToData:mp3Data
                                                 name:@"bar.mp3"
                                             MIMEType:nil];
NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithDataReference:dataReference error:&error];
[sound play];
</code>```

However, this forces me to completely download ALL of the MP3 synchronously before I can start playing it, which is obviously undesirable. Is there any way around this?

Thanks.

Edit

Actually, it seems that the path extension has nothing to do with it; the Content-Type is simply not being set in the HTTP header. Even so, the latter code works and the former does not. Anyone know of a way to fix this, without having access to the server?

Edit 2

Anyone? I can't find information about this anywhere, and Google frustratingly now shows this page as the top result for most of my queries...

答:
If you thought weichsel's first solution was hacky, you're going to love this one:

The culprit is the Content-Type header, as you have determined. Had QTKit.framework used Objective-C internally, this would be a trivial matter of overriding -[NSHTTPURLResponse allHeaderFields] with a category of your choosing. However, QTKit.framework (for better or worse) uses Core Foundation (and Core Services) internally. These are both C-based frameworks and there is no elegant way of overriding functions in C.

That said, there is a method, just not a pretty one. Function interposition is even documented by Apple, but seems to be a bit behind the times, compared to the remainder of their documentation.

In essence, you want something along the following lines:

```<code>typedef struct interpose_s {
    void *new_func;
    void *orig_func;
} interpose_t;

CFStringRef myCFHTTPMessageCopyHeaderFieldValue (
                                                 CFHTTPMessageRef message,
                                                 CFStringRef headerField
                                                 );

static const interpose_t interposers[] __attribute__ ((section("__DATA, __interpose"))) = {
    { (void *)myCFHTTPMessageCopyHeaderFieldValue, (void *)CFHTTPMessageCopyHeaderFieldValue }
};

CFStringRef myCFHTTPMessageCopyHeaderFieldValue (
                                                 CFHTTPMessageRef message,
                                                 CFStringRef headerField
                                                 ) {
    if (CFStringCompare(headerField, CFSTR("Content-Type"), 0) == kCFCompareEqualTo) {
        return CFSTR("audio/x-mpeg");
    } else {
        return CFHTTPMessageCopyHeaderFieldValue(message, headerField);
    }
}
</code>```

You might want to add logic specific to your application in terms of handling the Content-Type field lest your application break in weird and wonderful ways when every HTTP request is determined to be an audio file.

Body:
I'm using QTKit to progressively download and play an MP3 from a URL. According to this documentation, this is the code I should use to accomplish that:

NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar.mp3"];

NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithURL:mp3URL error:&error];
[sound play];

This works, and does exactly what I want — the MP3 URL is lazily downloaded and starts playing immediately. However, if the URL does not have the ".mp3" path extension, it fails:

NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar"];

NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithURL:mp3URL error:&error];
[sound play];

No error is given, no exception is raised; the duration of the sound is just set to zero, and nothing plays.

The only way I have found to work around this is to force a type by loading the data manually and using a QTDataReference:

NSURL *mp3URL = [NSURL URLWithString:@"http://foo.com/bar"];
NSData *mp3Data = [NSData dataWithContentsOfURL:mp3URL];

QTDataReference *dataReference =
    [QTDataReference dataReferenceWithReferenceToData:mp3Data
                                                 name:@"bar.mp3"
                                             MIMEType:nil];
NSError *error = nil;
QTMovie *sound = [[QTMovie alloc] initWithDataReference:dataReference error:&error];
[sound play];

However, this forces me to completely download ALL of the MP3 synchronously before I can start playing it, which is obviously undesirable. Is there any way around this?

Thanks.

Edit

Actually, it seems that the path extension has nothing to do with it; the Content-Type is simply not being set in the HTTP header. Even so, the latter code works and the former does not. Anyone know of a way to fix this, without having access to the server?

Edit 2

Anyone? I can't find information about this anywhere, and Google frustratingly now shows this page as the top result for most of my queries...

Body:
If you thought weichsel's first solution was hacky, you're going to love this one:

The culprit is the Content-Type header, as you have determined. Had QTKit.framework used Objective-C internally, this would be a trivial matter of overriding -[NSHTTPURLResponse allHeaderFields] with a category of your choosing. However, QTKit.framework (for better or worse) uses Core Foundation (and Core Services) internally. These are both C-based frameworks and there is no elegant way of overriding functions in C.

That said, there is a method, just not a pretty one. Function interposition is even documented by Apple, but seems to be a bit behind the times, compared to the remainder of their documentation.

In essence, you want something along the following lines:

typedef struct interpose_s {
    void *new_func;
    void *orig_func;
} interpose_t;

CFStringRef myCFHTTPMessageCopyHeaderFieldValue (
                                                 CFHTTPMessageRef message,
                                                 CFStringRef headerField
                                                 );

static const interpose_t interposers[] __attribute__ ((section("__DATA, __interpose"))) = {
    { (void *)myCFHTTPMessageCopyHeaderFieldValue, (void *)CFHTTPMessageCopyHeaderFieldValue }
};

CFStringRef myCFHTTPMessageCopyHeaderFieldValue (
                                                 CFHTTPMessageRef message,
                                                 CFStringRef headerField
                                                 ) {
    if (CFStringCompare(headerField, CFSTR("Content-Type"), 0) == kCFCompareEqualTo) {
        return CFSTR("audio/x-mpeg");
    } else {
        return CFHTTPMessageCopyHeaderFieldValue(message, headerField);
    }
}

You might want to add logic specific to your application in terms of handling the Content-Type field lest your application break in weird and wonderful ways when every HTTP request is determined to be an audio file.


来源: stackexchange

问:
numpy.hstack with strings and numbers removes decimals
I am trying to create a table to export in CSV. I have to attach different numerical values (with decimals), and I would like also to attach an indicator column. This is formed by empty spaces '_' and 'X', in order to help me with the post-process of the data.
As you can see in the code below, while I append only numerical values the decimals are present, whereas if I append the string column the decimals values disappears.

I think I will use numerical values also for the indicator column, but I would like to understand this behaviour. Is it possible to attach string columns and numerical values avoiding the elimination of the decimals?

```<code>>>> c = np.hstack((b,error_perc_notabs_array,error_array))
>>> c
array([[  3.63200000e-01,   6.52800000e-01,   4.70400000e-01,
          2.13117665e-02,   2.52124411e-02,   1.83029153e+01,
          3.90067457e-03],
       [  4.16000000e-01,   7.82400000e-01,   4.48000000e-01,
          2.25692703e-02,   4.35769819e-02,   9.30810405e+01,
          2.10077116e-02]])
>>> z
[array([' '],
      dtype='|S1'), array(['X'],
      dtype='|S1')]
>>> shape(z)
(2L, 1L)
>>> d = np.hstack((z,c))
>>> d
array([[' ', '0', '0', '0', '0', '0', '1', '0'],
       ['X', '0', '0', '0', '0', '0', '9', '0']],
      dtype='|S1')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a table to export in CSV. I have to attach different numerical values (with decimals), and I would like also to attach an indicator column. This is formed by empty spaces '_' and 'X', in order to help me with the post-process of the data.
As you can see in the code below, while I append only numerical values the decimals are present, whereas if I append the string column the decimals values disappears.

I think I will use numerical values also for the indicator column, but I would like to understand this behaviour. Is it possible to attach string columns and numerical values avoiding the elimination of the decimals?

>>> c = np.hstack((b,error_perc_notabs_array,error_array))
>>> c
array([[  3.63200000e-01,   6.52800000e-01,   4.70400000e-01,
          2.13117665e-02,   2.52124411e-02,   1.83029153e+01,
          3.90067457e-03],
       [  4.16000000e-01,   7.82400000e-01,   4.48000000e-01,
          2.25692703e-02,   4.35769819e-02,   9.30810405e+01,
          2.10077116e-02]])
>>> z
[array([' '],
      dtype='|S1'), array(['X'],
      dtype='|S1')]
>>> shape(z)
(2L, 1L)
>>> d = np.hstack((z,c))
>>> d
array([[' ', '0', '0', '0', '0', '0', '1', '0'],
       ['X', '0', '0', '0', '0', '0', '9', '0']],
      dtype='|S1')

Body:
Numpy convert all elements to a common datatype, which is, in your case S1, strings of length 1.

Despite this, my test shows, that the common datatype os S1 and float is S32:

>>> z = array([['X'],[' ']], dtype='S1')
>>> d = numpy.hstack((z,c))
>>> d
array([[b'X', b'0.3632', b'0.6528', b'0.4704', b'0.0213117665',
        b'0.0252124411', b'18.3029153', b'0.00390067457'],
       [b' ', b'0.416', b'0.7824', b'0.448', b'0.0225692703',
        b'0.0435769819', b'93.0810405', b'0.0210077116']],
      dtype='|S32')


问:
keepalived transitions not happening as expected
I am trying to implement keepalived based failover for my service. Please find below my configurations for the master and backup nodes.

Master node:

```<code>vrrp_script chk_splunkd {
    script "pidof splunkd"
    interval 2
    fall 2
    rise 2
}

vrrp_instance VI_1 {
    interface eth0
    state MASTER
    advert_int 1
    virtual_router_id 51
    priority 200
    nopreempt
    smtp_alert
    authentication {
            auth_type PASS
            auth_pass passme
    }
    virtual_ipaddress {
            10.126.246.245
    }
    track_script {
            chk_splunkd
    }
    notify_master /etc/keepalived/scripts/master.sh
    notify_backup /etc/keepalived/scripts/stop_service.sh
    notify_fault /etc/keepalived/scripts/stop_service.sh
}
</code>```

Back up node:

```<code>vrrp_script chk_splunkd {
    script "pidof splunkd"
    interval 2
    fall 2
    rise 2
}
vrrp_instance VI_1 {
    interface eth0
    state BACKUP
    advert_int 1
    virtual_router_id 51
    priority 100
    nopreempt
    smtp_alert
    authentication {
            auth_type PASS
            auth_pass passme
    }

    virtual_ipaddress {
           10.126.246.245
    }
    track_script {
            chk_splunkd
    }
    notify_master /etc/keepalived/scripts/master.sh
    notify_backup /etc/keepalived/scripts/stop_service.sh
    notify_fault /etc/keepalived/scripts/stop_service.sh
}
</code>```

However, I find that even when one node goes into fault state and stops sending VRRP advertisements, the other node doesn't automatically transition to master state. When I tried to monitor the VRRP advertisement packets using tcpdump -vv -i eth0 vrrp I find that even after the advertisement from one node stops, the other node doesn't automatically start sending the advertisements indicating that it has now become the master.

Please help me find out what I'm missing.

Thanks,

Keerthana

答: The issue was that during startup when one node became the master, the other one went into fault mode due to the pidof splunkd command which will return 1 as my splunk service should be up on only the master node. Once I edited the notify script to write current state to an external file and read the state to take action in my notify scripts, things started working fine.

Body:
I am trying to implement keepalived based failover for my service. Please find below my configurations for the master and backup nodes.

Master node:

vrrp_script chk_splunkd {
    script "pidof splunkd"
    interval 2
    fall 2
    rise 2
}

vrrp_instance VI_1 {
    interface eth0
    state MASTER
    advert_int 1
    virtual_router_id 51
    priority 200
    nopreempt
    smtp_alert
    authentication {
            auth_type PASS
            auth_pass passme
    }
    virtual_ipaddress {
            10.126.246.245
    }
    track_script {
            chk_splunkd
    }
    notify_master /etc/keepalived/scripts/master.sh
    notify_backup /etc/keepalived/scripts/stop_service.sh
    notify_fault /etc/keepalived/scripts/stop_service.sh
}

Back up node:

vrrp_script chk_splunkd {
    script "pidof splunkd"
    interval 2
    fall 2
    rise 2
}
vrrp_instance VI_1 {
    interface eth0
    state BACKUP
    advert_int 1
    virtual_router_id 51
    priority 100
    nopreempt
    smtp_alert
    authentication {
            auth_type PASS
            auth_pass passme
    }

    virtual_ipaddress {
           10.126.246.245
    }
    track_script {
            chk_splunkd
    }
    notify_master /etc/keepalived/scripts/master.sh
    notify_backup /etc/keepalived/scripts/stop_service.sh
    notify_fault /etc/keepalived/scripts/stop_service.sh
}

However, I find that even when one node goes into fault state and stops sending VRRP advertisements, the other node doesn't automatically transition to master state. When I tried to monitor the VRRP advertisement packets using tcpdump -vv -i eth0 vrrp I find that even after the advertisement from one node stops, the other node doesn't automatically start sending the advertisements indicating that it has now become the master.

Please help me find out what I'm missing.

Thanks,

Keerthana


问:
Looping for N Number of Sheets - Excel VBA
I have a template sheet. Then depending on the input on another sheet, template sheet will be copied N times and renamed as N. What I want to do now is to create a loop to transfer data from the sheets to a destination.

So example, from the Start sheet, (where the number input will come from), let's say I typed 5 since I want to have 5 sheets from the template. This will be renamed as 1...2...3...4...5.

And then, afterwards, once I've used these numbered sheets, I want to copy the data from these sheet to destination sheet. How do I do that?

In hand, I have the code for duplication and renaming of the worksheets and the following codes.

PS. How do I simplify the insert N cells to the left? Thank you so much. :)

```<code>    Sub CreateLoaderBeta1()

        Dim origin      As Worksheet
        Dim destination As Worksheet
        Dim desrow      As Long
        Dim descol      As Long
        Dim descolstart As Long
        Dim origrow     As Long
        Dim origcol     As Long
        Dim rang        As Range
        Dim C           As Range
        Dim qual        As Integer

        Set origin = Sheets("1")
        Set destination = Sheets("OFFLIMITS")
        desrow = 1
        descol = 1
        origrow = 18
        origcol = 32
        Set rng = origin.Range("AF18:af47")
        total = WorksheetFunction.SUM(origin.Range("AF18:AF47"))
        descolstart = destination.cells(desrow, Columns.Count).End(xlToLeft).column
        descolnext = descolstart + 1

        If total > 0 Then

                For Each C In rng
                    If C = 14 Then

                    'No,Type,Amount,Distribution Account,Description,Product Type,VAT,Ewt,Net Purchases,Yes/No,Enter

                            destination.cells(desrow, descolstart).Value = origin.cells(origrow, 1).Value 'to copy sequence number
                            destination.cells(desrow, descolstart + 1).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 2).Value = origin.cells(origrow, 4).Value 'type
                            destination.cells(desrow, descolstart + 3).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 4).Value = origin.cells(origrow, 27).Value 'amount
                            destination.cells(desrow, descolstart + 5).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 6).Value = origin.cells(origrow, 6).Value 'distribution account
                            destination.cells(desrow, descolstart + 7).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 8).Value = origin.cells(origrow, 30).Value 'description
                            destination.cells(desrow, descolstart + 9).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 10).Value = origin.cells(origrow, 9).Value 'product type
                            destination.cells(desrow, descolstart + 11).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 12).Value = origin.cells(origrow, 10).Value 'VAT
                            destination.cells(desrow, descolstart + 13).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 14).Value = origin.cells(origrow, 11).Value 'wht
                            destination.cells(desrow, descolstart + 15).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 16).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 17).Value = "Net Purchases" 'to Net Purchases
                            destination.cells(desrow, descolstart + 18).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 19).Value = origin.cells(origrow, 13).Value 'wht
                            destination.cells(desrow, descolstart + 20).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 21).Value = "\{ENTER}" 'to insert tab
                            destination.cells(desrow, descolstart + 22).Value = "\{DOWN}" 'to insert tab

                            descolstart = descolstart + 23
                            origrow = origrow + 1

                    End If
                Next C

                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column).Value = "\%C"
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column + 1).Value = "\%V"
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column + 1).Value = "\%K"

                'Call headers

                        Dim originWS    As Worksheet
                        Dim desWS       As Worksheet
                        Dim rowNO       As Integer

                        Set originWS = origin 'CHANGE THIS TO SHEET NUMBER
                        Set desWS = destination
                        rowNO = desrow

                        desWS.Range("A" & rowNO).Value = originWS.Range("C1").Value
                        desWS.Range("c" & rowNO).Value = originWS.Range("C2").Value
                        desWS.Range("e" & rowNO).Value = Worksheets("Start").Range("C22").Value
                        desWS.Range("H" & rowNO).Value = originWS.Range("C3").Value
                        desWS.Range("J" & rowNO).Value = originWS.Range("C4").Value
                        desWS.Range("L" & rowNO).Value = originWS.Range("C4").Value
                        desWS.Range("N" & rowNO).Value = originWS.Range("C5").Value
                        desWS.Range("P" & rowNO).Value = originWS.Range("C6").Value
                        desWS.Range("R" & rowNO).Value = originWS.Range("C7").Value
                        desWS.Range("T" & rowNO).Value = originWS.Range("C8").Value

                        'to insert the keystrokes
                        desWS.Range("B" & rowNO).Value = "\{TAB}"
                        desWS.Range("D" & rowNO).Value = "\{TAB}"
                        desWS.Range("F" & rowNO).Value = "\{TAB}"
                        desWS.Range("G" & rowNO).Value = "\{TAB}"
                        desWS.Range("I" & rowNO).Value = "\{TAB}"
                        desWS.Range("K" & rowNO).Value = "\{TAB}"
                        desWS.Range("M" & rowNO).Value = "\{TAB}"
                        desWS.Range("O" & rowNO).Value = "\{TAB}"
                        desWS.Range("Q" & rowNO).Value = "\{TAB}"
                        desWS.Range("S" & rowNO).Value = "\{TAB}"
                        desWS.Range("U" & rowNO).Value = "\%2"

                destination.Columns("J:J").NumberFormat = "dd-mmm-yy"
                destination.Columns("L:L").NumberFormat = "dd-mmm-yy"

        Else 'Do nothing

        End If

        End Sub
</code>```

答:
This question is actually threefold. The first part: Get n sheets generated with name "1", "2", etc. up to "n". Let us say that in Worksheet("Sheet1") in Range A1 you set the number of sheets you wish to generate. The script would then be:

```<code>Sub GenerateSheets()
Dim i as Integer
Dim numberOfSheets as Integer
Dim ws as Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").value

For i = 1 to numberOfSheets
    Set ws = Worksheets.add()
    With ws
        .name = i
        'Do other stuff with the new sheet
    End With
Next i
End Sub
</code>```

If these new sheets need to be copies of a template sheet, you could do:

```<code>Sub GenerateSheets()
Dim i As Integer
Dim numberOfSheets As Integer
Dim ws As Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").Value

For i = 1 To numberOfSheets
    Worksheets("Template").Copy After:=Worksheets("Template")
    Set ws = Worksheets(Worksheets("Template").Index + 1)
    With ws
        .Name = i
        'Do other stuff with the new sheet
    End With
Next i
End Sub
</code>```

The second question is: How do I get data from this worksheet back to my destination sheet? You could either just set values in "Destination" to be equal to values in your worksheet, or copy the entire cells. Based on your sample script, I'd say the first one has preference.
Let's say that you wish to copy the value from Range A1 in the new sheet to Range A1 in the destination. You can then amend the above as follows:

```<code>Sub GenerateSheets()
Dim i as Integer
Dim numberOfSheets as Integer
Dim ws as Worksheet
Dim destination as Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").value

Set destination = Worksheets("Destination")

For i = 1 to numberOfSheets
    Set ws = Worksheets.add()
    With ws
        .name = i
        .Range("A1") = "Some value"
        destination.Range("A1").value = .Range("A1").value ' = "Some value"
        'Do other stuff with the new sheet
    End With
Next i
End Sub
</code>```

The third part of the question:
"How do I simplify the insert N cells to the left?"
This depends on how many cells you wish to insert, but let's say it's X cells, the simplest way based on your existing code would be to resize the range to insert:

destination.cells(desrow, 1).Resize(1, X).insert Shift:=xlToRight

Body:
I have a template sheet. Then depending on the input on another sheet, template sheet will be copied N times and renamed as N. What I want to do now is to create a loop to transfer data from the sheets to a destination.

So example, from the Start sheet, (where the number input will come from), let's say I typed 5 since I want to have 5 sheets from the template. This will be renamed as 1...2...3...4...5.

And then, afterwards, once I've used these numbered sheets, I want to copy the data from these sheet to destination sheet. How do I do that?

In hand, I have the code for duplication and renaming of the worksheets and the following codes.

PS. How do I simplify the insert N cells to the left? Thank you so much. :)

    Sub CreateLoaderBeta1()

        Dim origin      As Worksheet
        Dim destination As Worksheet
        Dim desrow      As Long
        Dim descol      As Long
        Dim descolstart As Long
        Dim origrow     As Long
        Dim origcol     As Long
        Dim rang        As Range
        Dim C           As Range
        Dim qual        As Integer

        Set origin = Sheets("1")
        Set destination = Sheets("OFFLIMITS")
        desrow = 1
        descol = 1
        origrow = 18
        origcol = 32
        Set rng = origin.Range("AF18:af47")
        total = WorksheetFunction.SUM(origin.Range("AF18:AF47"))
        descolstart = destination.cells(desrow, Columns.Count).End(xlToLeft).column
        descolnext = descolstart + 1

        If total > 0 Then

                For Each C In rng
                    If C = 14 Then

                    'No,Type,Amount,Distribution Account,Description,Product Type,VAT,Ewt,Net Purchases,Yes/No,Enter

                            destination.cells(desrow, descolstart).Value = origin.cells(origrow, 1).Value 'to copy sequence number
                            destination.cells(desrow, descolstart + 1).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 2).Value = origin.cells(origrow, 4).Value 'type
                            destination.cells(desrow, descolstart + 3).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 4).Value = origin.cells(origrow, 27).Value 'amount
                            destination.cells(desrow, descolstart + 5).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 6).Value = origin.cells(origrow, 6).Value 'distribution account
                            destination.cells(desrow, descolstart + 7).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 8).Value = origin.cells(origrow, 30).Value 'description
                            destination.cells(desrow, descolstart + 9).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 10).Value = origin.cells(origrow, 9).Value 'product type
                            destination.cells(desrow, descolstart + 11).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 12).Value = origin.cells(origrow, 10).Value 'VAT
                            destination.cells(desrow, descolstart + 13).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 14).Value = origin.cells(origrow, 11).Value 'wht
                            destination.cells(desrow, descolstart + 15).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 16).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 17).Value = "Net Purchases" 'to Net Purchases
                            destination.cells(desrow, descolstart + 18).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 19).Value = origin.cells(origrow, 13).Value 'wht
                            destination.cells(desrow, descolstart + 20).Value = "\{TAB}" 'to insert tab
                            destination.cells(desrow, descolstart + 21).Value = "\{ENTER}" 'to insert tab
                            destination.cells(desrow, descolstart + 22).Value = "\{DOWN}" 'to insert tab

                            descolstart = descolstart + 23
                            origrow = origrow + 1

                    End If
                Next C

                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, 1).insert Shift:=xlToRight
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column).Value = "\%C"
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column + 1).Value = "\%V"
                destination.cells(desrow, destination.cells(desrow, Columns.Count).End(xlToLeft).column + 1).Value = "\%K"

                'Call headers

                        Dim originWS    As Worksheet
                        Dim desWS       As Worksheet
                        Dim rowNO       As Integer

                        Set originWS = origin 'CHANGE THIS TO SHEET NUMBER
                        Set desWS = destination
                        rowNO = desrow

                        desWS.Range("A" & rowNO).Value = originWS.Range("C1").Value
                        desWS.Range("c" & rowNO).Value = originWS.Range("C2").Value
                        desWS.Range("e" & rowNO).Value = Worksheets("Start").Range("C22").Value
                        desWS.Range("H" & rowNO).Value = originWS.Range("C3").Value
                        desWS.Range("J" & rowNO).Value = originWS.Range("C4").Value
                        desWS.Range("L" & rowNO).Value = originWS.Range("C4").Value
                        desWS.Range("N" & rowNO).Value = originWS.Range("C5").Value
                        desWS.Range("P" & rowNO).Value = originWS.Range("C6").Value
                        desWS.Range("R" & rowNO).Value = originWS.Range("C7").Value
                        desWS.Range("T" & rowNO).Value = originWS.Range("C8").Value

                        'to insert the keystrokes
                        desWS.Range("B" & rowNO).Value = "\{TAB}"
                        desWS.Range("D" & rowNO).Value = "\{TAB}"
                        desWS.Range("F" & rowNO).Value = "\{TAB}"
                        desWS.Range("G" & rowNO).Value = "\{TAB}"
                        desWS.Range("I" & rowNO).Value = "\{TAB}"
                        desWS.Range("K" & rowNO).Value = "\{TAB}"
                        desWS.Range("M" & rowNO).Value = "\{TAB}"
                        desWS.Range("O" & rowNO).Value = "\{TAB}"
                        desWS.Range("Q" & rowNO).Value = "\{TAB}"
                        desWS.Range("S" & rowNO).Value = "\{TAB}"
                        desWS.Range("U" & rowNO).Value = "\%2"

                destination.Columns("J:J").NumberFormat = "dd-mmm-yy"
                destination.Columns("L:L").NumberFormat = "dd-mmm-yy"

        Else 'Do nothing

        End If

        End Sub

Body:
This question is actually threefold. The first part: Get n sheets generated with name "1", "2", etc. up to "n". Let us say that in Worksheet("Sheet1") in Range A1 you set the number of sheets you wish to generate. The script would then be:

Sub GenerateSheets()
Dim i as Integer
Dim numberOfSheets as Integer
Dim ws as Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").value

For i = 1 to numberOfSheets
    Set ws = Worksheets.add()
    With ws
        .name = i
        'Do other stuff with the new sheet
    End With
Next i
End Sub

If these new sheets need to be copies of a template sheet, you could do:

Sub GenerateSheets()
Dim i As Integer
Dim numberOfSheets As Integer
Dim ws As Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").Value

For i = 1 To numberOfSheets
    Worksheets("Template").Copy After:=Worksheets("Template")
    Set ws = Worksheets(Worksheets("Template").Index + 1)
    With ws
        .Name = i
        'Do other stuff with the new sheet
    End With
Next i
End Sub

The second question is: How do I get data from this worksheet back to my destination sheet? You could either just set values in "Destination" to be equal to values in your worksheet, or copy the entire cells. Based on your sample script, I'd say the first one has preference.
Let's say that you wish to copy the value from Range A1 in the new sheet to Range A1 in the destination. You can then amend the above as follows:

Sub GenerateSheets()
Dim i as Integer
Dim numberOfSheets as Integer
Dim ws as Worksheet
Dim destination as Worksheet

numberOfSheets = Worksheets("Sheet1").Range("A1").value

Set destination = Worksheets("Destination")

For i = 1 to numberOfSheets
    Set ws = Worksheets.add()
    With ws
        .name = i
        .Range("A1") = "Some value"
        destination.Range("A1").value = .Range("A1").value ' = "Some value"
        'Do other stuff with the new sheet
    End With
Next i
End Sub

The third part of the question:
"How do I simplify the insert N cells to the left?"
This depends on how many cells you wish to insert, but let's say it's X cells, the simplest way based on your existing code would be to resize the range to insert:

destination.cells(desrow, 1).Resize(1, X).insert Shift:=xlToRight


问:
pull property object as parent object
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

```<code>let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]
</code>```

How can I group school first? I need the format to be like this

```<code>[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]
</code>```

答:
you can use lodash library with groupBy

```<code>let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

var result2 = _.chain(x)
    .groupBy(function(o){return o.school.name})
    .pairs()
    .map(function (currentItem) {
        return _.object(_.zip(["school", "name"], currentItem));
    })
    .value();
console.log(result2);
</code>```

check this jsFiddle :-
http://jsfiddle.net/6yasy30a/

Title: pull property object as parent object

Body:
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

How can I group school first? I need the format to be like this

[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]

Body:
you can use lodash library with groupBy

let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

var result2 = _.chain(x)
    .groupBy(function(o){return o.school.name})
    .pairs()
    .map(function (currentItem) {
        return _.object(_.zip(["school", "name"], currentItem));
    })
    .value();
console.log(result2);

check this jsFiddle :-
http://jsfiddle.net/6yasy30a/


问:
Get contact number from contact list in BlackBerry
When the user clicks a button in my app, I want to open the contact list for the user to select a contact.  I then want to get the phone number for the selected contact.</p>

答:
you can use BlackBerryContactList.choose().</p>

```<code>BlackBerryContactList list = (BlackBerryContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
        PIMItem contact = list.choose();
        if(contact != null){
            String mobileNumber="";
            for(int i=0; i < contact.countValues(Contact.TEL); i++)
            {
                if(contact.getAttributes(Contact.TEL, i) == Contact.ATTR_MOBILE)
                    mobileNumber = contact.getString(Contact.TEL, i);
            }
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
you can use BlackBerryContactList.choose().

BlackBerryContactList list = (BlackBerryContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
        PIMItem contact = list.choose();
        if(contact != null){
            String mobileNumber="";
            for(int i=0; i < contact.countValues(Contact.TEL); i++)
            {
                if(contact.getAttributes(Contact.TEL, i) == Contact.ATTR_MOBILE)
                    mobileNumber = contact.getString(Contact.TEL, i);
            }
        }


问:
Class name conflict with class in Framework
In main project, I have a class named: Result.

And I import a third framework through Cocoapods which is also named Result. The Result framework has a class named Result.

In project, how can I use the Result class in Result framework?

答:
You need to put the package name in front of the class name.

```<code>ThirdPartyFrameworkName.Result
</code>```

and

```<code>YourTargetName.Result
</code>```

Body:
You need to put the package name in front of the class name.

ThirdPartyFrameworkName.Result

and

YourTargetName.Result


问:
Laravel 5 exception "The Symfony\Component\Process\ProcessUtils::escapeArgument() is deprecated"
I get everytime ErrorException when I want to execute any command using artisan, phpunit.

How can I fix it?

```<code>The Symfony\Component\Process\ProcessUtils::escapeArgument() method is deprecated since version 3.3 and will be removed in 4.0. Use a command line array or give env vars to the Process::start/run() method instead. C:\xampp\htdocs\mee2\vendor\symfony\process\ProcessUtils.php:43
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Application.php:68
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Application.php:89
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Scheduling\Schedule.php:69
C:\xampp\htdocs\mee2\app\Console\Kernel.php:28
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:101
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:86
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:827
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:776
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\BootProviders.php:17
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:208
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:267
C:\xampp\htdocs\mee2\tests\CreatesApplication.php:18
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:89
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:66
C:\xampp\htdocs\mee2\tests\TestCase.php:15
</code>```

composer.json

```<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "adamwathan/bootforms": "^0.8.4",
        "dimsav/laravel-translatable": "^7.0",
        "laracasts/utilities": "^2.1",
        "laravel/dusk": "^1.0",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "laravelista/ekko": "^1.3",
        "maatwebsite/excel": "^2.1",
        "sentry/sentry": "^1.6",
        "sentry/sentry-laravel": "^0.6.1",
        "sofa/model-locking": "~5.3",
        "spatie/laravel-medialibrary": "^5.8",
        "spatie/laravel-migrate-fresh": "^1.4",
        "spatie/laravel-model-cleanup": "^1.2",
        "venturecraft/revisionable": "1.*"
    },
    "require-dev": {
        "barryvdh/laravel-ide-helper": "^2.3",
        "doctrine/dbal": "^2.5",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/Helpers/functions.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}
</code>```

Laravel 5 is on xampp, php 7, apache, windows 10

I don't have the same problem on other computer with the same installation

答: Did you run composer update in your project folder?

Body:
I get everytime ErrorException when I want to execute any command using artisan, phpunit.

How can I fix it?

The Symfony\Component\Process\ProcessUtils::escapeArgument() method is deprecated since version 3.3 and will be removed in 4.0. Use a command line array or give env vars to the Process::start/run() method instead. C:\xampp\htdocs\mee2\vendor\symfony\process\ProcessUtils.php:43
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Application.php:68
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Application.php:89
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Console\Scheduling\Schedule.php:69
C:\xampp\htdocs\mee2\app\Console\Kernel.php:28
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:101
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:86
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:827
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:776
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\BootProviders.php:17
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:208
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:267
C:\xampp\htdocs\mee2\tests\CreatesApplication.php:18
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:89
C:\xampp\htdocs\mee2\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:66
C:\xampp\htdocs\mee2\tests\TestCase.php:15

composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "adamwathan/bootforms": "^0.8.4",
        "dimsav/laravel-translatable": "^7.0",
        "laracasts/utilities": "^2.1",
        "laravel/dusk": "^1.0",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "laravelista/ekko": "^1.3",
        "maatwebsite/excel": "^2.1",
        "sentry/sentry": "^1.6",
        "sentry/sentry-laravel": "^0.6.1",
        "sofa/model-locking": "~5.3",
        "spatie/laravel-medialibrary": "^5.8",
        "spatie/laravel-migrate-fresh": "^1.4",
        "spatie/laravel-model-cleanup": "^1.2",
        "venturecraft/revisionable": "1.*"
    },
    "require-dev": {
        "barryvdh/laravel-ide-helper": "^2.3",
        "doctrine/dbal": "^2.5",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/Helpers/functions.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

Laravel 5 is on xampp, php 7, apache, windows 10

I don't have the same problem on other computer with the same installation


问:
How to do SSRS report on azure platform as a service
We have planned to do SSRS on azure environment but our client not affordable to buy azure virtual machine. Can we do SSRS report on azure platform as a service (PaaS)?</p>

答:
SSRS is not supported on Azure SQL Database. You must have a virutal machine.
See how-to-setup-ssrs-with-an-azure-sql-server-database.

You should have a look on Power BI : you can make reports with this technology.


问:
Materialize navbar Show/Hide specific Menu based on Condition
I want to show/hide navbar user login.
in my case for eg i am having 2 types of user,
one user ca able to access 4 menu's and another can access 3 only.

like this image

I wish to set {display:none;} based on condition . i wish to write it under custom HTML attributes. how do i achieve this?

I need solution something like Angular ng-show/ ng-if

答:
You can add to body/html tag new class depending on your user and hide/show elements using css.

Or pass params (ex. ?user=admin) to url, check it using javascript and do what you want with DOM.


答:
You can use _.groupBy() and map the results back into array:

const data = [{"name":"james","age":10,"school":{"id":1,"name":"London"}},{"name":"james_2","age":11,"school":{"id":1,"name":"London"}},{"name":"john","age":12,"school":{"id":2,"name":"India"}},{"name":"johnny","age":56,"school":{"id":3,"name":"USA"}}];

const result = _(data)
  .groupBy('school.name')
  .map((group) => ({ // or Object.assign({}, group[0].school, { data: group });
    ...group[0].school,
    data: group
  }))
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

You can do the same things without lodash by using Array#reduce in combination with Map:

const data = [{"name":"james","age":10,"school":{"id":1,"name":"London"}},{"name":"james_2","age":11,"school":{"id":1,"name":"London"}},{"name":"john","age":12,"school":{"id":2,"name":"India"}},{"name":"johnny","age":56,"school":{"id":3,"name":"USA"}}];

const result = [...data.reduce((map, item) => {
  const school = map.get(item.school.name) || { // or Object.assign({}, { item.school }, { data: [] })
    ...item.school, data: []
  };

  school.data.push(item);

  map.set(item.school.name, school);

  return map;
}, new Map()).values()]

console.log(result);```

Title: pull property object as parent object

Body:
You can use _.groupBy() and map the results back into array:

const data = [{"name":"james","age":10,"school":{"id":1,"name":"London"}},{"name":"james_2","age":11,"school":{"id":1,"name":"London"}},{"name":"john","age":12,"school":{"id":2,"name":"India"}},{"name":"johnny","age":56,"school":{"id":3,"name":"USA"}}];

const result = _(data)
  .groupBy('school.name')
  .map((group) => ({ // or Object.assign({}, group[0].school, { data: group });
    ...group[0].school,
    data: group
  }))
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

You can do the same things without lodash by using Array#reduce in combination with Map:

const data = [{"name":"james","age":10,"school":{"id":1,"name":"London"}},{"name":"james_2","age":11,"school":{"id":1,"name":"London"}},{"name":"john","age":12,"school":{"id":2,"name":"India"}},{"name":"johnny","age":56,"school":{"id":3,"name":"USA"}}];

const result = [...data.reduce((map, item) => {
  const school = map.get(item.school.name) || { // or Object.assign({}, { item.school }, { data: [] })
    ...item.school, data: []
  };

  school.data.push(item);

  map.set(item.school.name, school);

  return map;
}, new Map()).values()]

console.log(result);


问:
How do I access the MediaMetadataRetriever.setDataSource(...) status codes?
I'm getting the following error java.lang.RuntimeException: setDataSource failed: status = 0xFFFFFFEA and I'd like to know what this status is. I'm using the function MediaMetaDataRetriever.setDataSource(String filePath)

答:
I got this error java.lang.RuntimeException: setDataSource failed: status = 0xFFFFFFEA  when tried to call void setDataSource(String path) on an empty file. (0 bytes)

You need to be 100% sure that path for the file is not null, not empty, the file itself exists and valid.


问:
Transitioning away from Object.observe
I've been using Object.observe() as part of a nw.js project that is now transitioning from nw.js v.0.12.3 to latest.

I have code like this:

```<code>..(myclass)..
data: { a:0, b:42 },
setupHandlers: function () {
    Object.observe(this.data, changes => this.draw());
},
draw: function () { .. }
</code>```

My initial conversion looks like:

```<code>data: {_a: 0, _b: 42},
get a() { return this._a; }
set a(val) { this.data._a = val; this.draw(); }
get b() { return this._b; }
set b(val) { this.data._b = val; this.draw(); }
</code>```

and then change every place that wrote to data (myobj.data.a = 1) to instead write to the object (myobj.a = 1), thus using the setter.

It's a very labor-intensive conversion, is there an easier way?

答:
We ended up using Proxy to catch attribute assignment:

```<code>const shallow_observer = function (obj, fn) {
    return new Proxy(obj, {
        set(target, name, val) {
            target[name] = val;
            if (fn) fn(target, name, val);
            return true;
        }
    });
};
</code>```

which allowed us to do:

```<code>data: { a:0, b:42 },
setupHandlers: function () {
    this.data = shallow_observer(this.data, (data, field, value) => this.draw());
},
draw: function () { .. }
</code>```

We have a deep_observer function too (which is much more complex), that detects changes in a nested data structure, but the shallow_observer was sufficient for all our use-cases.

Title: Transitioning away from Object.observe

Body:
I've been using Object.observe() as part of a nw.js project that is now transitioning from nw.js v.0.12.3 to latest.

I have code like this:

..(myclass)..
data: { a:0, b:42 },
setupHandlers: function () {
    Object.observe(this.data, changes => this.draw());
},
draw: function () { .. }

My initial conversion looks like:

data: {_a: 0, _b: 42},
get a() { return this._a; }
set a(val) { this.data._a = val; this.draw(); }
get b() { return this._b; }
set b(val) { this.data._b = val; this.draw(); }

and then change every place that wrote to data (myobj.data.a = 1) to instead write to the object (myobj.a = 1), thus using the setter.

It's a very labor-intensive conversion, is there an easier way?

Body:
We ended up using Proxy to catch attribute assignment:

const shallow_observer = function (obj, fn) {
    return new Proxy(obj, {
        set(target, name, val) {
            target[name] = val;
            if (fn) fn(target, name, val);
            return true;
        }
    });
};

which allowed us to do:

data: { a:0, b:42 },
setupHandlers: function () {
    this.data = shallow_observer(this.data, (data, field, value) => this.draw());
},
draw: function () { .. }

We have a deep_observer function too (which is much more complex), that detects changes in a nested data structure, but the shallow_observer was sufficient for all our use-cases.


问:
Is there a fast way in Python to read in data from a file, separated by empty lines?
I want to read in data from a txt file that looks like this:

```<code># input data
50.  310.  3.0E-07  23.06
50.  310.5  2.4E-07  5.73

50.5  310.  2.9E-07  16.30
50.5  310.5  2.2E-07  4.26

51.  310.  2.3E-07  6.40
51.  310.5  2.7E-07  8.19
</code>```

So I have different blocks, each with a few lines of data and four values, who all end with a blank line.

Currently I read in my data with numpy like this, which gives me an array for every value from all the different blocks.

```<code> x,y,z,err = np.loadtxt(path_to_file, unpack=True)
</code>```

But in fact I'm really interested to get a list of list for each value, so that I can separate the data from each block, which is indicated through a blank line in the datafile.
The results, for example for the third value, should look like this:

```<code># the result i want to achieve
z_list = array([[3.0E-7, 2.4E-07],
   [2.9E-07, 2.2E-07],
   [2.3E-07, 2.7E-07]])
</code>```

Is there a way in Python or numpy where I read my data and separate it by blank lines?

答:
You can achieve the same result without importing external modules.

```<code>def read_data(filename):
    """
    filename    :   "/Users/.../Desktop/.../filename.txt"
    """
    datafile = list(open(filename, 'r'))
    # 4 columns in your example
    col_1, col_2, col_3, col_4 = [], [], [], []
    for col in datafile:
        data = col.split()
        col_1.append(float(data[0])) # 1st column
        col_2.append(float(data[1]))
        col_3.append(float(data[2]))
        col_4.append(float(data[3]))
    return col_1, col_2, col_3, col_4
</code>```

Then you could achieve the list of list output like this:

```<code>data_1, data_2, data_3, data_4 = read_data(filename)
data = [data_1, data_2, data_3, data_4]
</code>```

Body:
I want to read in data from a txt file that looks like this:

# input data
50.  310.  3.0E-07  23.06
50.  310.5  2.4E-07  5.73

50.5  310.  2.9E-07  16.30
50.5  310.5  2.2E-07  4.26

51.  310.  2.3E-07  6.40
51.  310.5  2.7E-07  8.19

So I have different blocks, each with a few lines of data and four values, who all end with a blank line.

Currently I read in my data with numpy like this, which gives me an array for every value from all the different blocks.

 x,y,z,err = np.loadtxt(path_to_file, unpack=True)

But in fact I'm really interested to get a list of list for each value, so that I can separate the data from each block, which is indicated through a blank line in the datafile.
The results, for example for the third value, should look like this:

# the result i want to achieve
z_list = array([[3.0E-7, 2.4E-07],
   [2.9E-07, 2.2E-07],
   [2.3E-07, 2.7E-07]])

Is there a way in Python or numpy where I read my data and separate it by blank lines?

Body:
You can achieve the same result without importing external modules.

def read_data(filename):
    """
    filename    :   "/Users/.../Desktop/.../filename.txt"
    """
    datafile = list(open(filename, 'r'))
    # 4 columns in your example
    col_1, col_2, col_3, col_4 = [], [], [], []
    for col in datafile:
        data = col.split()
        col_1.append(float(data[0])) # 1st column
        col_2.append(float(data[1]))
        col_3.append(float(data[2]))
        col_4.append(float(data[3]))
    return col_1, col_2, col_3, col_4

Then you could achieve the list of list output like this:

data_1, data_2, data_3, data_4 = read_data(filename)
data = [data_1, data_2, data_3, data_4]


问:
how to kill mysql process using mac
I used ps ax | grep mysql to check whether mysql process exists and i found

5323 s000  S+     0:00.00 grep mysql .

I would like to kill the process but the number changed automatically.

When i enter ps ax | grep mysql, the content changed like

5507 s000  S+     0:00.00 grep mysql

BTW, i have tried the way to deleted mysql that is the most popular way on the internet. But the mysql process still on my computer.

Anyone could give me a hint would be highly appreciated.

答:
just did it. I tried:
1) get pid

```<code>netstat -vanp tcp | grep 3306
</code>```

or

```<code>ps ax | grep mysql
</code>```

2) sudo kill -9 [pid]
It seems that I killed it right? but wait... when show mysql pid again, it comes back again with a different pid. Then I remember mysql in system preferences. Press the icon, and press stop server button. SUCCESS

EDIT: it is here

Title: how to kill mysql process using mac

Body:
just did it. I tried:
1) get pid

netstat -vanp tcp | grep 3306

or

ps ax | grep mysql

2) sudo kill -9 [pid]
It seems that I killed it right? but wait... when show mysql pid again, it comes back again with a different pid. Then I remember mysql in system preferences. Press the icon, and press stop server button. SUCCESS

EDIT: it is here

ContentLicense: CC BY-SA 4.0


问:
Reproducing CRAN GCC-UBSAN test results 'at home' on ubuntu
I'm scratching my head on this one. How to reproduce
 the results of CRAN's gcc ubsan tests of my package at home, on ubuntu? (the instructions on the preparation steps come from here)

1) I install-update all needed packages:

```<code>apt-get update
apt-get install bash-completion bison debhelper default-jdk g++ gcc gfortran groff-base libblas-dev libbz2-dev libcairo2-dev libcurl4-openssl-dev libjpeg-dev liblapack-dev liblzma-dev libncurses5-dev libpango1.0-dev libpcre3-dev libpng-dev libreadline-dev libtiff5-dev libx11-dev libxt-dev mpack subversion tcl8.5-dev texinfo texlive-base texlive-extra-utils texlive-fonts-extra texlive-fonts-recommended texlive-generic-recommended texlive-latex-base texlive-latex-extra texlive-latex-recommended tk8.5-dev valgrind x11proto-core-dev xauth xdg-utils xfonts-base xvfb zlib1g-dev
</code>```

2) Built Rdevel with the needed options:

```<code>cd /tmp
svn co http://svn.r-project.org/R/trunk R-devel
cd /tmp/R-devel
R_PAPERSIZE=letter R_BATCHSAVE="--no-save --no-restore" PAGER=/usr/bin/pager  PERL=/usr/bin/perl  R_UNZIPCMD=/usr/bin/unzip  R_ZIPCMD=/usr/bin/zip  R_PRINTCMD=/usr/bin/lpr  LIBnn=lib  AWK=/usr/bin/awk  CFLAGS="-pipe -std=gnu99 -Wall -pedantic -O2"  CXXFLAGS="-pipe -Wall -pedantic -O2"  CC="gcc -fsanitize=address,undefined"  CXX="g++ -fsanitize=address,undefined"  CXX1X="g++ -fsanitize=address,undefined"  FC="gfortran -fsanitize=address,undefined"  F77="gfortran -fsanitize=address,undefined" ./configure --enable-R-shlib --without-blas --without-lapack --with-readline --without-recommended-packages --program-suffix=dev --disable-openmp
make
make install
make clean
</code>```

3) finally, build/compile said package locally with the as-cran flag:

```<code>wget https://cran.r-project.org/src/contrib/FastRCS_0.0.6.tar.gz
tar -xvzf FastRCS_0.0.6.tar.gz
Rdevel CMD check --as-cran FastRCS
</code>```

But I don't get the same bug report as on cran (see here). I mean for example this one:

```<code>/usr/local/gcc5/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/emmintrin.h:140:21: runtime error: load of misaligned address 0x61800007fc84 for type 'const double', which requires 8 byte alignment
0x61800007fc84: note: pointer points here
  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f
</code>```

What is wrong with the script I use?

答:
Another out-of-the-box solution seems to be using r-hub package / service, that works in similar fashion as devtools::check(), you just need to run

```<code>rhub::check_with_sanitizers()
</code>```

Body:
I'm scratching my head on this one. How to reproduce
 the results of CRAN's gcc ubsan tests of my package at home, on ubuntu? (the instructions on the preparation steps come from here)

1) I install-update all needed packages:

apt-get update
apt-get install bash-completion bison debhelper default-jdk g++ gcc gfortran groff-base libblas-dev libbz2-dev libcairo2-dev libcurl4-openssl-dev libjpeg-dev liblapack-dev liblzma-dev libncurses5-dev libpango1.0-dev libpcre3-dev libpng-dev libreadline-dev libtiff5-dev libx11-dev libxt-dev mpack subversion tcl8.5-dev texinfo texlive-base texlive-extra-utils texlive-fonts-extra texlive-fonts-recommended texlive-generic-recommended texlive-latex-base texlive-latex-extra texlive-latex-recommended tk8.5-dev valgrind x11proto-core-dev xauth xdg-utils xfonts-base xvfb zlib1g-dev

2) Built Rdevel with the needed options:

cd /tmp
svn co http://svn.r-project.org/R/trunk R-devel
cd /tmp/R-devel
R_PAPERSIZE=letter R_BATCHSAVE="--no-save --no-restore" PAGER=/usr/bin/pager  PERL=/usr/bin/perl  R_UNZIPCMD=/usr/bin/unzip  R_ZIPCMD=/usr/bin/zip  R_PRINTCMD=/usr/bin/lpr  LIBnn=lib  AWK=/usr/bin/awk  CFLAGS="-pipe -std=gnu99 -Wall -pedantic -O2"  CXXFLAGS="-pipe -Wall -pedantic -O2"  CC="gcc -fsanitize=address,undefined"  CXX="g++ -fsanitize=address,undefined"  CXX1X="g++ -fsanitize=address,undefined"  FC="gfortran -fsanitize=address,undefined"  F77="gfortran -fsanitize=address,undefined" ./configure --enable-R-shlib --without-blas --without-lapack --with-readline --without-recommended-packages --program-suffix=dev --disable-openmp
make
make install
make clean

3) finally, build/compile said package locally with the as-cran flag:

wget https://cran.r-project.org/src/contrib/FastRCS_0.0.6.tar.gz
tar -xvzf FastRCS_0.0.6.tar.gz
Rdevel CMD check --as-cran FastRCS

But I don't get the same bug report as on cran (see here). I mean for example this one:

/usr/local/gcc5/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/emmintrin.h:140:21: runtime error: load of misaligned address 0x61800007fc84 for type 'const double', which requires 8 byte alignment
0x61800007fc84: note: pointer points here
  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f  00 00 80 3f 00 00 80 3f

What is wrong with the script I use?

Body:
Another out-of-the-box solution seems to be using r-hub package / service, that works in similar fashion as devtools::check(), you just need to run

rhub::check_with_sanitizers()


问:
Does dereferencing a pointer make a copy of it?
Does dereferencing a pointer and passing that to a function which takes its argument by reference create a copy of the object?</p>

答:
Hopefully it does not : it would if the called function takes its argument by value.

Furthermore, that's the expected behavior of a reference :

```<code>void inc(int &i) { ++i; }

int main()
{
    int i = 0;
    int *j = &i;
    inc(*j);
    std::cout << i << std::endl;
}
</code>```

This code is expected to print 1 because inc takes its argument by reference. Had a copy been made upon inc call, the code would print 0.

Body:
Hopefully it does not : it would if the called function takes its argument by value.

Furthermore, that's the expected behavior of a reference :

void inc(int &i) { ++i; }

int main()
{
    int i = 0;
    int *j = &i;
    inc(*j);
    std::cout << i << std::endl;
}

This code is expected to print 1 because inc takes its argument by reference. Had a copy been made upon inc call, the code would print 0.


问:
SignalR and WebAPI
I want to send notifications to web page, which is a client WebAPI.
So, I have 2 solutions, Asp.Net MVC application and WebAPI application. I have added SignalR nuget to both. WebAPI part has the following code:

```<code>public class ProgressHub : Hub
{
    public void Notification(string message)
    {
        Clients.Caller.onProgressNotification(message);
    }
}

private void SendMessage(string message)
{
    var context = Microsoft.AspNet.SignalR
        .GlobalHost.ConnectionManager.GetHubContext<Hubs.ProgressHub>();
    context.Clients.All.onProgressNotification(message);
}
</code>```

and then call it from my controller Action:

```<code>public async Task<IHttpActionResult> ZonalPost()
{
    SendMessage("Start");
    // my long operation
    SendMessage("Scan complete");
    // my long operation
    SendMessage("Convert complete");
    // my long operation
</code>```

And in my web application (client part):

```<code><script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
    $(function () {
        var progress = $.connection.progressHub;

        progress.client.onProgressNotification = function (message) {
            console.log(message);
        };
    });
</code>```

but I got an error

430 Uncaught TypeError: Cannot read property 'client' of undefined

Why and how to solve?

答:
You may need to use something like the following:

```<code>$(function () {
    $.connection.hub.url = '<yourbackendurl>';
    var connection = $.hubConnection();
    var progress = connection.createHubProxy('progressHub');
    progress.on('onProgressNotification', function(message) {
        console.log(message);
    });
    connection.start()
        .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
        .fail(function(){ console.log('Could not connect'); });
});
</code>```

See the docs on using SignalR without the generated proxy. Note that you also need to specify the server URL if you're connecting to a different server.

Title: SignalR and WebAPI

Body:
I want to send notifications to web page, which is a client WebAPI.
So, I have 2 solutions, Asp.Net MVC application and WebAPI application. I have added SignalR nuget to both. WebAPI part has the following code:

public class ProgressHub : Hub
{
    public void Notification(string message)
    {
        Clients.Caller.onProgressNotification(message);
    }
}

private void SendMessage(string message)
{
    var context = Microsoft.AspNet.SignalR
        .GlobalHost.ConnectionManager.GetHubContext<Hubs.ProgressHub>();
    context.Clients.All.onProgressNotification(message);
}

and then call it from my controller Action:

public async Task<IHttpActionResult> ZonalPost()
{
    SendMessage("Start");
    // my long operation
    SendMessage("Scan complete");
    // my long operation
    SendMessage("Convert complete");
    // my long operation

And in my web application (client part):

Body:
You may need to use something like the following:

$(function () {
    $.connection.hub.url = '<yourbackendurl>';
    var connection = $.hubConnection();
    var progress = connection.createHubProxy('progressHub');
    progress.on('onProgressNotification', function(message) {
        console.log(message);
    });
    connection.start()
        .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
        .fail(function(){ console.log('Could not connect'); });
});

See the docs on using SignalR without the generated proxy. Note that you also need to specify the server URL if you're connecting to a different server.


问:
Searching Expandable Listview with onGroupClick & onChildClick showing wrong results
i have problem with my onClick after searching in my expandable listview. When i search i get the right results, but when i Toast the values when i click them individually, i get different results? Kindly help

My method to filter my data for search

```<code>public void filterData(String query){
    query=query.toLowerCase();
    parentRowArrayList.clear();

    if(query.isEmpty()){
        parentRowArrayList.addAll(originalList);
    }else{
        for(ParentRow parentRow:originalList){
            ArrayList<ChildRow> childList = parentRow.getChildList();
            ArrayList<ChildRow> newList = new ArrayList<>();

            for(ChildRow childRow:childList){
                if(childRow.getText().toLowerCase().contains(query)){
                    Toast.makeText(context, childRow.getText().toString(), Toast.LENGTH_SHORT).show();
                    newList.add(childRow);
                }
            }//end for ChildRow childRow:childList

            if(newList.size()>0){
                ParentRow newParentRow = new ParentRow(parentRow.getName(),newList);

                parentRowArrayList.add(newParentRow);
            }
        } // end for ParentRow parentRow:originalList
    } //end else

    notifyDataSetChanged();
}
</code>```

My OnChildClickListener

```<code>        myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(),
                                  parentRowArrayList.get(groupPosition).getChildList()
                                          .get(childPosition).getText() +"",
                        Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });
</code>```

my OnGroupClickListener

```<code>   myList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                 Toast.makeText(getApplicationContext(),
                 "Group Clicked " + parentRowArrayList.get(groupPosition).getName(),
                 Toast.LENGTH_SHORT).show();
                return false;
            }
        });
</code>```

SearchView Implemented Methods

```<code>   @Override
public boolean onClose() {
    listAdapter.filterData("");
    expandAll();
    return false;
}

@Override
public boolean onQueryTextChange(String query) {
    listAdapter.filterData(query);
    myList.setAdapter(listAdapter);
    listAdapter.notifyDataSetChanged();
    expandAll();
    return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
    listAdapter.filterData(query);
    myList.setAdapter(listAdapter);
    listAdapter.notifyDataSetChanged();
    expandAll();
    return false;
}
</code>```

答: Because the filterData method is in adapter class and it refers to the same instance member variable(i.e parentRowArrayList) and OnChildClickListener part of your activity so, these two different methods pointing to the two different data sources. If you refer the 'arraylist' from the adapter in  OnChildClickListener method will get the same result. </p>

Body:
i have problem with my onClick after searching in my expandable listview. When i search i get the right results, but when i Toast the values when i click them individually, i get different results? Kindly help

My method to filter my data for search

public void filterData(String query){
    query=query.toLowerCase();
    parentRowArrayList.clear();

    if(query.isEmpty()){
        parentRowArrayList.addAll(originalList);
    }else{
        for(ParentRow parentRow:originalList){
            ArrayList<ChildRow> childList = parentRow.getChildList();
            ArrayList<ChildRow> newList = new ArrayList<>();

            for(ChildRow childRow:childList){
                if(childRow.getText().toLowerCase().contains(query)){
                    Toast.makeText(context, childRow.getText().toString(), Toast.LENGTH_SHORT).show();
                    newList.add(childRow);
                }
            }//end for ChildRow childRow:childList

            if(newList.size()>0){
                ParentRow newParentRow = new ParentRow(parentRow.getName(),newList);

                parentRowArrayList.add(newParentRow);
            }
        } // end for ParentRow parentRow:originalList
    } //end else

    notifyDataSetChanged();
}

My OnChildClickListener

        myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(),
                                  parentRowArrayList.get(groupPosition).getChildList()
                                          .get(childPosition).getText() +"",
                        Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });

my OnGroupClickListener

   myList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                 Toast.makeText(getApplicationContext(),
                 "Group Clicked " + parentRowArrayList.get(groupPosition).getName(),
                 Toast.LENGTH_SHORT).show();
                return false;
            }
        });

SearchView Implemented Methods

   @Override
public boolean onClose() {
    listAdapter.filterData("");
    expandAll();
    return false;
}

@Override
public boolean onQueryTextChange(String query) {
    listAdapter.filterData(query);
    myList.setAdapter(listAdapter);
    listAdapter.notifyDataSetChanged();
    expandAll();
    return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
    listAdapter.filterData(query);
    myList.setAdapter(listAdapter);
    listAdapter.notifyDataSetChanged();
    expandAll();
    return false;
}


问:
i need to allow the data which is in between the start and end date
Here i given my database table. i need to create a code to allow the data to show after the start date and remove the data after the end date:

答:
```<code>SELECT column1,column2 From table_name where start_date BETWEEN start_date AND end_date AND end_date BETWEEN start_date AND end_date
</code>```


问:
laravel5.4 validate can not show $errors
I use validate to confirm register form .
`$message = array('required' => 'you can not');

```<code>    $datavalidate = array(
        'phone' =>$request->input('phone')
    );
    $rules = array(
        'phone' =>'required'
    );

    $validator = Validator::make($datavalidate,$rules,$message);
    if($validator->fails())
    {
        return Redirect::back()->withErrors($validator);

    }

    $this->validate($request,[
        'phone' => 'required',
        'confirmCode' => 'required'
    ]);`
</code>```

two way both can not get $errors.
 I can sure this validate worked.throw a exception,because after validate method ,all code not excuse.
 But I can get $errors,maybe direct wrong url?
this is include in register web.
`

```<code>    <ul>
        <li>hello</li>
        @foreach($errors->all() as $error)
            <li>{{$error}}</li>
            @endforeach
    </ul>
{{var_dump($errors)}}
</code>```

this list can not show any $error.Is there not direct last url .
UPDATE:this is form.

```<code>            <form class="form-horizontal" action="{{route('confirmRegister')}}"method="post" onsubmit="return postForm()">

            {{csrf_field()}}
            <div class="form-group">
                <label for="mobileNum" class="col-xs-3 control-label text-center">手机号</label>
                <div class="col-xs-8">
                    <input type="text" name="phone" class="form-control" id="mobileNum" placeholder="手机号码">
                </div>
            </div>

            <div class="form-group">

                <label for="passWord" class="col-xs-3 text-center">密码</label>
                <div class="col-xs-8">
                    <input type="password" class="form-control" id="passWord" placeholder="密码">
                    <input type="hidden" id="sendPassWord" name="passWord">
                    <input type="hidden" id="openId" name="openId">
                </div>
            </div>

            <div class="form-group">

                <label for="confirmPassWord" class="col-xs-3 text-center">确认密码</label>
                <div class="col-xs-8">
                    <input type="password" name="confirmPassWord" class="form-control" id="confirmPassWord" placeholder="确认密码">
                </div>
            </div>

            <div class="form-group">
                <label for="confirm" class="col-xs-3 text-center">验证码</label>
                <div class="col-xs-5">
                    <input type="text" name="confirmCode" class="form-control" id="confirm" placeholder="短信验证码">
                </div>
                <div class="col-xs-4">
                    <button type="button" class="btn btn-info btn-block" id="getConfirm">获取验证码</button>
                </div>
            </div>
            <div class="alert alert-danger alert-dismissible col-xs-offset-3 col-xs-8" role="alert" style="display: none" id="codeError">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                <strong>错误!</strong> 获取验证码失败！
            </div>

            <div class="form-group">
                <div class="col-xs-offset-3 col-xs-8">
                    <button type="submit" class="btn btn-primary btn-block" id="register">注册</button>
                </div>
            </div>

        </form>
</code>```

UPDATE:

```<code>        function postForm() {

        var passWord = md5( $('#passWord').val() );
        $('#sendPassWord').val(passWord);

        $('#openId').val("{{$openId}}");

        return true;

    }
</code>```

答:
```<code>    phone<input type="text" name="phone" >
    <span class="error">{{$errors->first('phone')}}</span>

    confirmCode<input type="text" name="confirmCode">
    <span class="error">{{$errors->first('confirmCode')}}</span>
</code>```

controller codes

```<code>     $rules = ['phone' => 'required',
            'confirmCode' => 'required',

        ];
        $message = [
            'phone.required' => 'enter your phone number',
            'confirmCode.required' => 'confirm your code

        ];
        $validator = validator::make($request->input(), $rules, $message);
        if ($validator->fails()) {
            return back()
                ->WithErrors($validator)
                ->WithInput();
}else{    write your codes here
</code>```

try this one. set your rules and message in this way

Body:
I use validate to confirm register form .
`$message = array('required' => 'you can not');

    $datavalidate = array(
        'phone' =>$request->input('phone')
    );
    $rules = array(
        'phone' =>'required'
    );

    $validator = Validator::make($datavalidate,$rules,$message);
    if($validator->fails())
    {
        return Redirect::back()->withErrors($validator);

    }

    $this->validate($request,[
        'phone' => 'required',
        'confirmCode' => 'required'
    ]);`

two way both can not get $errors.
 I can sure this validate worked.throw a exception,because after validate method ,all code not excuse.
 But I can get $errors,maybe direct wrong url?
this is include in register web.
`

hello

        @foreach($errors->all() as $error)

{{$error}}

            @endforeach

{{var_dump($errors)}}

this list can not show any $error.Is there not direct last url .
UPDATE:this is form.

            <form class="form-horizontal" action="{{route('confirmRegister')}}"method="post" onsubmit="return postForm()">

            {{csrf_field()}}

                手机号

                    <input type="text" name="phone" class="form-control" id="mobileNum" placeholder="手机号码">

                密码

                    <input type="password" class="form-control" id="passWord" placeholder="密码">
                    <input type="hidden" id="sendPassWord" name="passWord">
                    <input type="hidden" id="openId" name="openId">

                确认密码

                    <input type="password" name="confirmPassWord" class="form-control" id="confirmPassWord" placeholder="确认密码">

                验证码

                    <input type="text" name="confirmCode" class="form-control" id="confirm" placeholder="短信验证码">

                    <button type="button" class="btn btn-info btn-block" id="getConfirm">获取验证码</button>

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                错误! 获取验证码失败！

                    <button type="submit" class="btn btn-primary btn-block" id="register">注册</button>

        </form>

UPDATE:

        function postForm() {

        var passWord = md5( $('#passWord').val() );
        $('#sendPassWord').val(passWord);

        $('#openId').val("{{$openId}}");

        return true;

    }

Body:
    phone<input type="text" name="phone" >
    <span class="error">{{$errors->first('phone')}}</span>

    confirmCode<input type="text" name="confirmCode">
    <span class="error">{{$errors->first('confirmCode')}}</span>

controller codes

     $rules = ['phone' => 'required',
            'confirmCode' => 'required',

        ];
        $message = [
            'phone.required' => 'enter your phone number',
            'confirmCode.required' => 'confirm your code

        ];
        $validator = validator::make($request->input(), $rules, $message);
        if ($validator->fails()) {
            return back()
                ->WithErrors($validator)
                ->WithInput();
}else{    write your codes here

try this one. set your rules and message in this way


问:
How to execute stored procedures by Order in SQL Server
I have created a stored procedure which calls other stored procedures but I don't want to execute them at the same time. Stored procedure #1 execution takes time so when it finishes stored procedure #2 will start to execute.

How can I do this?

```<code>EXEC SP1;
--wait for SP1 to finish its job
EXEC SP2;
</code>```

Any suggestions?

答:
It should be as simple as </p>

```<code>EXEC SP1;
GO
EXEC SP2;
GO
</code>```

Body:
I have created a stored procedure which calls other stored procedures but I don't want to execute them at the same time. Stored procedure #1 execution takes time so when it finishes stored procedure #2 will start to execute.

How can I do this?

EXEC SP1;
--wait for SP1 to finish its job
EXEC SP2;

Any suggestions?

Body:
It should be as simple as

EXEC SP1;
GO
EXEC SP2;
GO


问:
string split based on char \
Got a bit of a mind freeze at the moment.
I have the following syntax:-

```<code>        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');
</code>```

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

答: Typically, the \ character is meant to escape other characters. If you wish it to be taken literally, you need to escape it with another \. So, in order to escape on backslashes, you'll provide \\.

Title: string split based on char \

Body:
Got a bit of a mind freeze at the moment.
I have the following syntax:-

        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

OwnerDisplayName: Jonathan Sampson


问:
Hide a dynamic element function on.('hide')
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

```<code>function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}
</code>```

答:
According to the documentation you should use hidden.bs.modal event. Also no need in checking the window object for the function, just pass it.

$('#myModal').modal('show');

var close_function = function () {
  console.log('closed');
}

$('#myModal').on('hidden.bs.modal', close_function);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" id='myModal' abindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div></code>```

Body:
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}

Body:
According to the documentation you should use hidden.bs.modal event. Also no need in checking the window object for the function, just pass it.

$('#myModal').modal('show');

var close_function = function () {
  console.log('closed');
}

$('#myModal').on('hidden.bs.modal', close_function);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" id='myModal' abindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
SFDC Twilio Outbound Call
I am doing a POC and trying to make an outbound call through Twilio from Salesforce. I already have an account in Twilio.

I have configured TWIML apps and pointed the Requested URL with SFDC URL: https://xxxxxx.cs8.force.com/Dial.

I am able to connect from my SFDC softphone (laptop microphone) to the customer (To number) but I would like to connect through my From (Agent Physical Phone) to To phone #.

Even though I have hardcoded From Phone in the 'From','To','Url' => 'http://xxx-xxx.cs8.force.com/Dial parameter for Twilio Call, call is going from Softphone to Physical and not getting the call on my #(From).

I believe Twilio should connect both From and To #. Any help is greatly appreciated.

```<code>public class testtwilio {
String account = 'Axxxxxxx';
String token = 'dyyyyyyyyy';
public PageReference hello(){
    TwilioRestClient client = new TwilioRestClient(account, token);
    Map<String,String> properties = new Map<String,String> {
        'To'   => '+11234567890',            '
        'From' => '+15555555555',
        'Url' => 'https://demo.twilio.com/welcome/voice/'    };
TwilioCall Call = client.getAccount().getCalls().create(properties);return null;
}
</code>```

}

答:
Twilio developer evangelist here.

You need to set the callerId on the <Dial> that you use to connect the outgoing call to your customer. That will make the number appear as your Twilio number.

Title: SFDC Twilio Outbound Call

Body:
I am doing a POC and trying to make an outbound call through Twilio from Salesforce. I already have an account in Twilio.

I have configured TWIML apps and pointed the Requested URL with SFDC URL: https://xxxxxx.cs8.force.com/Dial.

I am able to connect from my SFDC softphone (laptop microphone) to the customer (To number) but I would like to connect through my From (Agent Physical Phone) to To phone #.

Even though I have hardcoded From Phone in the 'From','To','Url' => 'http://xxx-xxx.cs8.force.com/Dial parameter for Twilio Call, call is going from Softphone to Physical and not getting the call on my #(From).

I believe Twilio should connect both From and To #. Any help is greatly appreciated.

public class testtwilio {
String account = 'Axxxxxxx';
String token = 'dyyyyyyyyy';
public PageReference hello(){
    TwilioRestClient client = new TwilioRestClient(account, token);
    Map<String,String> properties = new Map<String,String> {
        'To'   => '+11234567890',            '
        'From' => '+15555555555',
        'Url' => 'https://demo.twilio.com/welcome/voice/'    };
TwilioCall Call = client.getAccount().getCalls().create(properties);return null;
}

}


问:
asp.net c# Regular Expression Validator for formatted numbers
I have a textbox with a numeric value. For example The number is 23542.56. The number is stored as double in an MySQL Database.

I convert the number to decimal and format it as string while I load the value from the database with thousands separator with ...ToString("N").

```<code>TextBox.Text = Convert.ToDecimal(mdr["Value"].ToString()).ToString("N");
</code>```

My Regular Expression Validator accepts only digits and commas:

```<code><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox" ValidationExpression="^\d+(\,\d+$)?$" ValidationGroup="NumericValidate">Allowed Chars are: 0-9 und ,</asp:RegularExpressionValidator>
</code>```

The problem is that the Validator does not accept the formatted number, for exampel 23.542,56. What is a proper way to make him accept only "0-9 and ," but also accept the thousands separator?

Thanks in advance...

Info: To show "28542.56" as "23.542,56" is the common notation in germany, that is the reason why I format the number this way.

答:
You don't need to escape the comma , but you have to escape the dot ., otherwise it will match every character, as in .*, which matches everything.

The [ square brackets ] match any character in the given class, which contains dot ., comma , and digits.

If you want to be more strict and have triplets and such you must do:

```<code>  thousands v          v literal comma
^\d{1,3}(?:\.\d{3})*(?:,\d*)?$
         ^           ^ non-capturing-groups
</code>```

This will still match ill-formed numbers with leading zeroes 0 such as:

```<code>00
01
003.999,99
</code>```

There's a very easy way to exclude those, too. I leave it to you as homework :)
Hint: [1-9]

EDIT: accept only 1 1,11 1.111 1.111,11 1111,11

The regex for this should be:

```<code>^1+(?:\.111)*(?:,11)?$
</code>```

It may be a little different for some corner cases, but that's basically it.

Body:
I have a textbox with a numeric value. For example The number is 23542.56. The number is stored as double in an MySQL Database.

I convert the number to decimal and format it as string while I load the value from the database with thousands separator with ...ToString("N").

TextBox.Text = Convert.ToDecimal(mdr["Value"].ToString()).ToString("N");

My Regular Expression Validator accepts only digits and commas:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox" ValidationExpression="^\d+(\,\d+$)?$" ValidationGroup="NumericValidate">Allowed Chars are: 0-9 und ,</asp:RegularExpressionValidator>

The problem is that the Validator does not accept the formatted number, for exampel 23.542,56. What is a proper way to make him accept only "0-9 and ," but also accept the thousands separator?

Thanks in advance...

Info: To show "28542.56" as "23.542,56" is the common notation in germany, that is the reason why I format the number this way.

Body:
You don't need to escape the comma , but you have to escape the dot ., otherwise it will match every character, as in .*, which matches everything.

The [ square brackets ] match any character in the given class, which contains dot ., comma , and digits.

If you want to be more strict and have triplets and such you must do:

  thousands v          v literal comma
^\d{1,3}(?:\.\d{3})*(?:,\d*)?$
         ^           ^ non-capturing-groups

This will still match ill-formed numbers with leading zeroes 0 such as:

00
01
003.999,99

There's a very easy way to exclude those, too. I leave it to you as homework :)
Hint: [1-9]

EDIT: accept only 1 1,11 1.111 1.111,11 1111,11

The regex for this should be:

^1+(?:\.111)*(?:,11)?$

It may be a little different for some corner cases, but that's basically it.


问:
How do you launch Safari browser from within an iPad app?

Possible Duplicate:

  launch safari from iphone app

How do you launch Safari browser from within an iPad app?

答:
Like this:</p>

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:yourURLHere]];
</code>```

Body:
Like this:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:yourURLHere]];