问:
Overriding HTTP client config while declaring routes
I have a web application from which I'm calling around 50-60 rest/soap apis. For this, I've created routes in JAVA DSL. Now, to have default application level timeout settings, I've done configuration like this-

```<code>public class DefaultHttpClientConfig implements HttpClientConfigurer {   // http4
    @Override
    public void configureHttpClient(HttpClientBuilder clientBuilder) {
            clientBuilder.setDefaultRequestConfig(
                            RequestConfig.custom()
                                    .setConnectTimeout(1000)
                                    .setSocketTimeout(1000).build());
    }
}
</code>```

and I've set this in camel context like this-

```<code>    static CamelContext ctx = new DefaultCamelContext();

    static {
            try {
                    HttpComponent httpComponent = ctx.getComponent("http4", HttpComponent.class);
                    httpComponent.setConnectionTimeToLive(10);
                    httpComponent.setHttpClientConfigurer(new DefaultHttpClientConfig());
                    ctx.addRoutes(new DirectRestRouteBuilder());
                    ctx.start();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }
</code>```

Now when creating individual routes, I want to override these configuration, so I'm trying this as shown below-

```<code>from("direct:success")
       .to("http4://localhost:8089/mockcarrier/success?httpClient.socketTimeout=8000");
</code>```

However, it seems that the direct configuration in JAVA DSL is not picked up. Where am I going wrong?

答:
Add DefaultHttpClientConfig to the Camel registry and set it on the route with the httpClientConfigurer parameter (Camel documentation).

Like this:

```<code>.to("http4://localhost:8089/mockcarrier/success?httpClientConfigurer=yourCustomConfigurerNameInTheRegistry");
</code>```

Body:
I have a web application from which I'm calling around 50-60 rest/soap apis. For this, I've created routes in JAVA DSL. Now, to have default application level timeout settings, I've done configuration like this-

public class DefaultHttpClientConfig implements HttpClientConfigurer {   // http4
    @Override
    public void configureHttpClient(HttpClientBuilder clientBuilder) {
            clientBuilder.setDefaultRequestConfig(
                            RequestConfig.custom()
                                    .setConnectTimeout(1000)
                                    .setSocketTimeout(1000).build());
    }
}

and I've set this in camel context like this-

    static CamelContext ctx = new DefaultCamelContext();

    static {
            try {
                    HttpComponent httpComponent = ctx.getComponent("http4", HttpComponent.class);
                    httpComponent.setConnectionTimeToLive(10);
                    httpComponent.setHttpClientConfigurer(new DefaultHttpClientConfig());
                    ctx.addRoutes(new DirectRestRouteBuilder());
                    ctx.start();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

Now when creating individual routes, I want to override these configuration, so I'm trying this as shown below-

from("direct:success")
       .to("http4://localhost:8089/mockcarrier/success?httpClient.socketTimeout=8000");

However, it seems that the direct configuration in JAVA DSL is not picked up. Where am I going wrong?

Body:
Add DefaultHttpClientConfig to the Camel registry and set it on the route with the httpClientConfigurer parameter (Camel documentation).

Like this:

.to("http4://localhost:8089/mockcarrier/success?httpClientConfigurer=yourCustomConfigurerNameInTheRegistry");


来源: stackexchange

问:
How to set column titles as subtitles in Python
I want to plot several graphs of an excel data in Python with a simple command. I am currently using the following code:

```<code>import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(12,12))
data_cols = df.columns[8:16]
for data_col, ax in zip(data_cols, axes.ravel()):
   ax.boxplot(df[data_col])
</code>```

I want to set column titles that I choose for data_cols as subtitles of subplots. Do you have an idea about how can I do that?
Thanks in advance.

答:
Of course you need to iterate over those axes and columns you want to plot to and from. So if you want to plot the last 8 columns of the dataframe you also need to iterate over the last 8 axes.

This would then allow you the use the column name as title, ax.set_title(data_col).

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(1)

a = np.random.rand(5, 16)
df = pd.DataFrame(a, columns=list("ABCDEFGHIJKLMNOP"))

fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(6,6), sharex=True, sharey=True)
data_cols = df.columns[8:16]
for data_col, ax in zip(data_cols, axes.ravel()[8:16]):
   ax.boxplot(df[data_col])
   ax.set_title(data_col)

plt.tight_layout()
plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to plot several graphs of an excel data in Python with a simple command. I am currently using the following code:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(12,12))
data_cols = df.columns[8:16]
for data_col, ax in zip(data_cols, axes.ravel()):
   ax.boxplot(df[data_col])

I want to set column titles that I choose for data_cols as subtitles of subplots. Do you have an idea about how can I do that?
Thanks in advance.

Body:
Of course you need to iterate over those axes and columns you want to plot to and from. So if you want to plot the last 8 columns of the dataframe you also need to iterate over the last 8 axes.

This would then allow you the use the column name as title, ax.set_title(data_col).

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(1)

a = np.random.rand(5, 16)
df = pd.DataFrame(a, columns=list("ABCDEFGHIJKLMNOP"))

fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(6,6), sharex=True, sharey=True)
data_cols = df.columns[8:16]
for data_col, ax in zip(data_cols, axes.ravel()[8:16]):
   ax.boxplot(df[data_col])
   ax.set_title(data_col)

plt.tight_layout()
plt.show()


问:
Drill Deeper In Recursive Processing
I have a folder that is three levels deep, each level contains a good amount of files. I am able to get two levels deep with the script below, however the third level is posing a bit of a challenge. Would someone mind offering some guidance as to how I am supposed to get one level deeper? Use python or another language wouldn't be acceptable, as I am trying to see how this works with AppleScript. </p>

```<code>set sourceFolder to (choose folder)

tell application "Finder"
    my changeFileNameCase(sourceFolder, "upper")
    repeat with subFolder in (get every folder of folder sourceFolder)
        my changeFileNameCase(subFolder as alias, "upper")

        #This Is No Good
        repeat with theFolder in (get every folder of folder subFolder)
            my changeFileNameCase(theFolder, "upper")
        end repeat

    end repeat
end tell

on changeFileNameCase(targetFolder, caseToSwitchTo)
    tell application "Finder"
        set fileList to every file of folder targetFolder
        repeat with theFile in fileList
            set oldName to name of theFile
            set newName to my changeCaseOfText(oldName, caseToSwitchTo)
            set the name of theFile to newName
        end repeat
    end tell
end changeFileNameCase
</code>```

答:
To make the handler recursive you have to get all items of the folder and check the class of each item.

If the class is folder call the handler passing the folder

If the class is file rename it

```<code>set sourceFolder to (choose folder)
changeFileNameCase(sourceFolder, "upper")

on changeFileNameCase(targetFolder, caseToSwitchTo)
    tell application "Finder"
        set theList to every item of targetFolder
        repeat with i from 1 to count theList
            set theItem to item i of theList
            if class of theItem is folder then
                my changeFileNameCase(theItem, caseToSwitchTo)
            else
                set oldName to name of theItem
                set newName to my changeCaseOfText(oldName, caseToSwitchTo)
                set name of theItem to newName
            end if
        end repeat
    end tell
end changeFileNameCase
</code>```

Title: Drill Deeper In Recursive Processing

Body:
I have a folder that is three levels deep, each level contains a good amount of files. I am able to get two levels deep with the script below, however the third level is posing a bit of a challenge. Would someone mind offering some guidance as to how I am supposed to get one level deeper? Use python or another language wouldn't be acceptable, as I am trying to see how this works with AppleScript.

set sourceFolder to (choose folder)

tell application "Finder"
    my changeFileNameCase(sourceFolder, "upper")
    repeat with subFolder in (get every folder of folder sourceFolder)
        my changeFileNameCase(subFolder as alias, "upper")

        #This Is No Good
        repeat with theFolder in (get every folder of folder subFolder)
            my changeFileNameCase(theFolder, "upper")
        end repeat

    end repeat
end tell

on changeFileNameCase(targetFolder, caseToSwitchTo)
    tell application "Finder"
        set fileList to every file of folder targetFolder
        repeat with theFile in fileList
            set oldName to name of theFile
            set newName to my changeCaseOfText(oldName, caseToSwitchTo)
            set the name of theFile to newName
        end repeat
    end tell
end changeFileNameCase

Body:
To make the handler recursive you have to get all items of the folder and check the class of each item.

If the class is folder call the handler passing the folder

If the class is file rename it

set sourceFolder to (choose folder)
changeFileNameCase(sourceFolder, "upper")

on changeFileNameCase(targetFolder, caseToSwitchTo)
    tell application "Finder"
        set theList to every item of targetFolder
        repeat with i from 1 to count theList
            set theItem to item i of theList
            if class of theItem is folder then
                my changeFileNameCase(theItem, caseToSwitchTo)
            else
                set oldName to name of theItem
                set newName to my changeCaseOfText(oldName, caseToSwitchTo)
                set name of theItem to newName
            end if
        end repeat
    end tell
end changeFileNameCase


问:
Build Application to Answer Phone Call and Delegate To iPhone's Phone Application
We want to build an application that the user can interact with while taking a phone call.  The idea is that the user can do voice communication using the phone application of the iPhone and at the same time use our application to type and send additional data that is relevant to the call such as an e-mail address.  This is the scenario:

User get's a call on the iPhone

The user clicks a button on our app to answer the call and let the phone application on the iPhone handle the phone call in the background.

Our application continues to run in the foreground so that the user can interact with our application to type and send data such as an e-mail address that is relevant to the call.

Is there a way for our application to answer an incoming phone call and let the phone application of the iPhone handle the call in the background while our application continues to run in the foreground?

Thanks,
Prasanna

答:
You have no control over the phone call process on an iPhone (this is assuming that you’re not talking about a jailbroken iPhone). When the user receives a call, the iPhone presents a window with the number and the “Answer” and “Ignore” buttons (or, if the phone is locked or asleep, the “Slide to Answer” bar). To return to your or any other application, the user must press the home button, sending the call to the background (and activating the red in-call status bar).

The closest you’ll get to this scenario is the user manually running the application while on the phone. But then, if all they’re doing is writing notes, they could just use the Notes app.

ContentLicense: CC BY-SA 2.5


问:
Calculating cumulative values for every 12 months on tables with possibly null values
I have this table:

```<code>Month       Year         MV                    MI         fullDate
-----------------------------------------------------------------
...
5           2015         1                      5         2015-05-01
6           2015         1                     10         2015-06-01
7           2015         3                     10         2015-07-01
8           2015         2                     10         2015-08-01
11          2015         1                     10         2015-11-01
1           2016         4                     10         2016-01-01
6           2016         1                     20         2016-06-01
7           2016         null                  10         2016-07-01
8           2016         2                      5         2016-08-01
...
</code>```

I need to create another table with cumulative values:

```<code>Month       Year         AMV                  AMI
-----------------------------------------------------------------
...
7           2015         3                     10
8           2015         5                     20
11          2015         6                     30
1           2016         10                    40
6           2016         11                    60
7           2016         0                     10
8           2016         2                     15
...
</code>```

The cumulative calculations must start on a July and end on June of the next year. In this example, the cumulative fields started "accumulating" from July, 2015 and ended on June, 2016. These calculations re-started on July, 2016 getting another cycle for cumulative values to "calculate"

I made a similar question before but I just found out this "periodicity" for calculations of cumulative. One more thing... some values on the first table could be null and need to be considered as 0.

Please, tell me how can this be done?

答:
This does the trick:</p>

```<code>SET @amv := 0, @ami := 0;

SELECT
  (@amv:=IF(ISNULL(MV), 0, @amv+MV)) as AMV,
  (@ami:=IF(ISNULL(MI), 0, @ami+MI)) as AMI,
  fullDate
FROM
  input
WHERE
  fullDate >= "2015-07-01" AND
  fullDate < "2016-07-01"
ORDER BY fullDate ASC;
</code>```

Body:
I have this table:

Month       Year         MV                    MI         fullDate
-----------------------------------------------------------------
...
5           2015         1                      5         2015-05-01
6           2015         1                     10         2015-06-01
7           2015         3                     10         2015-07-01
8           2015         2                     10         2015-08-01
11          2015         1                     10         2015-11-01
1           2016         4                     10         2016-01-01
6           2016         1                     20         2016-06-01
7           2016         null                  10         2016-07-01
8           2016         2                      5         2016-08-01
...

I need to create another table with cumulative values:

Month       Year         AMV                  AMI
-----------------------------------------------------------------
...
7           2015         3                     10
8           2015         5                     20
11          2015         6                     30
1           2016         10                    40
6           2016         11                    60
7           2016         0                     10
8           2016         2                     15
...

The cumulative calculations must start on a July and end on June of the next year. In this example, the cumulative fields started "accumulating" from July, 2015 and ended on June, 2016. These calculations re-started on July, 2016 getting another cycle for cumulative values to "calculate"

I made a similar question before but I just found out this "periodicity" for calculations of cumulative. One more thing... some values on the first table could be null and need to be considered as 0.

Please, tell me how can this be done?

Body:
This does the trick:

SET @amv := 0, @ami := 0;

SELECT
  (@amv:=IF(ISNULL(MV), 0, @amv+MV)) as AMV,
  (@ami:=IF(ISNULL(MI), 0, @ami+MI)) as AMI,
  fullDate
FROM
  input
WHERE
  fullDate >= "2015-07-01" AND
  fullDate < "2016-07-01"
ORDER BY fullDate ASC;


问:
List of Programs that PC ROM have, Which supports the UEFI
List of programs that UEFI ROM have, And how to call them from other programs</p>

答: Although this question should be closed as off-topic, UEFI doesn't have any programs. It's UEFI Shell which provides access to utils. You can download a shell from EDK II repository. Command reference can be found in Shell Specification</p>


问:
ExtJs: How can I select first item of Radiogroup on button click event
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

```<code>Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});
</code>```

Above code is not working. I have also tried below code. But it also doesn't work:

```<code>var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));
</code>```

答:
I'd like to discourage you from using Ext.ComponentQuery and long strings of items.items[] where possible - If more radiogroups are added to the page, or things are shuffled around in the future, you'll be running around to patch it up and tweak which item[x] or radiogroup[x] the handler is changing.

I'd propose adding a reference to the default radio you'd like:

```<code>reference: 'defaultRadio',
</code>```

And reaching it in the button handler by:

```<code>handler: function (button) {
    button.up("panel").down("radio[reference='defaultRadio']").setValue(true);
}
</code>```

Which you can see in this fiddle accomplishes the same thing, and is far more readable.

This will look at the panel containing the button, and find the radio with the reference defaultRadio that is contained within the same panel. This code would be easier to share within an application, and easy to change if you decide another radio should be default (i.e. just changing which radio has the reference).

Body:
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});

Above code is not working. I have also tried below code. But it also doesn't work:

var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));

Body:
I'd like to discourage you from using Ext.ComponentQuery and long strings of items.items[] where possible - If more radiogroups are added to the page, or things are shuffled around in the future, you'll be running around to patch it up and tweak which item[x] or radiogroup[x] the handler is changing.

I'd propose adding a reference to the default radio you'd like:

reference: 'defaultRadio',

And reaching it in the button handler by:

handler: function (button) {
    button.up("panel").down("radio[reference='defaultRadio']").setValue(true);
}

Which you can see in this fiddle accomplishes the same thing, and is far more readable.

This will look at the panel containing the button, and find the radio with the reference defaultRadio that is contained within the same panel. This code would be easier to share within an application, and easy to change if you decide another radio should be default (i.e. just changing which radio has the reference).


问:
How to fix Jenkins job that is failing on git checkout when workspace is on network share, but not when workspace is on local drive?
I'm building a service that creates dynamic nodes that will connect to a Jenkins server. The nodes will be used primarily for building many large code bases, so I would like to take advantage of incremental builds. Since the nodes are ephemeral virtual machines that get destroyed sometime after the job is complete, I need the Jenkins workspace to be something other than a local drive on the machine.

I created a network share and I set the root directory for the Jenkins node to I:\jenkins. When the VM comes online, my service executes a command that maps the I drive to the network share. The service then executes commands to connect the service to the Jenkins master. When I attempt to run a build against the node, it consistently fails when trying to git checkout.

After the job fails, the network share has most of the files from the git repository, so the share is accessible and there's no read/write restrictions preventing the job from running. This error happens with any job I try to run, including jobs that access git repos with very few files.

The log output in the failed Jenkins job is:

git checkout -f ...a70f
FATAL: Could not checkout ...a70f
hudson.plugins.git.GitException: Could not checkout ...a70f
...<stack trace>...
stderr: error: failed to read object ...f656 at offset ...1596 from .git/objects/pack/pack-...2475.pack
fatal: packed object ...f656 (stored in .git/objects/pack/pack-...2475.pack) is corrupt

If I change the workspace for the node to a local drive and reconnect the exact same machine and re-run the exact same job, I never see a failure. Git properly clones everything I need, and my job goes green.

How can I fix the issue I'm seeing with the network share? Or alternatively, how can I meet the following requirements:

The Jenkins nodes must run on ephemeral VMs that might be destroyed and recreated at any time

The workspace must be visible to multiple VMs concurrently (stringent workspace naming for the jobs prevents multiple nodes from reading/writing the same files)

The workspace must persist even if there are no Jenkins nodes online

Any new nodes that come online must be able to reconnect to the workspace

If there's a solution that doesn't require a network share, I would be happy to try something else!

答:
Found a solution here:
GIT pull error - remote object is corrupted

For some reason the default git config values work perfectly fine when the workspace is in local storage. When moving to any externally mapped storage solution the git config needed to be modified to prevent


问:
Mysql select first then limit
How can i select the newest 5 rows from mysql (newest by id for example) then order them asc or desc ??

the problem is i have 1,2,3,4,5,6,7 , i want to select the newest 2 for example (6,7) then order them asc or desc (6,7 or 7,6) , but if i use the orderby then the limit it would be (1,2) or (7,6) , is there anyway to do it from ONE sql statement ?

thank you

答:
I didn't get if you wanted the newest 5 or 2, I use 2 here. But here is something I just wrote without testing.

```<code>SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY id DESC LIMIT 2) ORDER BY id ASC/DESC;</code>```

Hope this will help! :)

Title: Mysql select first then limit

Body:
I didn't get if you wanted the newest 5 or 2, I use 2 here. But here is something I just wrote without testing.

SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY id DESC LIMIT 2) ORDER BY id ASC/DESC;

Hope this will help! :)


问:
jquery css selector to match elements with id contains specific text after the last dot
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

```<code><div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot
</code>```

答:
You can do something like this:

var ids = $('div');
$.each(ids,function(index,value){
  var ids_split = this.id.split('.'), id_length = ids_split.length, last_class=ids_split[id_length-1], search_term = "cow";
if (last_class.includes(search_term)) {

    $(this).addClass('cows_only');

     // only .cow is selected
}

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot</code>```

This iterates your divs and grabs the id whose last . has "cow" somewhere. Here is a fiddle:
jsfiddle

Notice how classes are only added to the divs with "cows" after the last dot.

Body:
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

 // get it

 //get it

 //DON'T get it - not after the last dot

Body:
You can do something like this:

var ids = $('div');
$.each(ids,function(index,value){
  var ids_split = this.id.split('.'), id_length = ids_split.length, last_class=ids_split[id_length-1], search_term = "cow";
if (last_class.includes(search_term)) {

    $(this).addClass('cows_only');

     // only .cow is selected
}

});

<div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot

This iterates your divs and grabs the id whose last . has "cow" somewhere. Here is a fiddle:
jsfiddle

Notice how classes are only added to the divs with "cows" after the last dot.


问:
Excel VBA - Bitcoin
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

```<code>Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub
</code>```

答:
There are two things going on here:

You are adding a query table and setting a variety of properties.  One of those properties is CommandType, which is of constant type XlCmdType.  You are setting that property to 0, which is not a valid value.  You can simply comment out (or delete) that line of code.  This will allow your code to run without error. However...

Every time you run this procedure, you will be adding a new query table.  What I imagine you are looking to do is simply refresh the data.  Once the Query Table has been added to your worksheet, you can simply run this code to refresh the data:

```<code>Sub RefreshQueryTable()

    ActiveSheet.QueryTables("tobtc?currency=USD&value=1_1").Refresh

End Sub
</code>```

Keep in mind, if you are using a keyboard shortcut, a user might invoke the shortcut from any sheet in the workbook, thus this code will fail if the user is not on the sheet that contains the Query Table.  You'd want to make sure you explicitly refer to the appropriate sheet:

```<code>Sub RefreshQueryTable()
    ThisWorkbook.Sheets("Sheet1").QueryTables("tobtc?currency=USD&value=1_1").Refresh
End Sub
</code>```

Title: Excel VBA - Bitcoin

Body:
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub

Body:
There are two things going on here:

You are adding a query table and setting a variety of properties.  One of those properties is CommandType, which is of constant type XlCmdType.  You are setting that property to 0, which is not a valid value.  You can simply comment out (or delete) that line of code.  This will allow your code to run without error. However...

Every time you run this procedure, you will be adding a new query table.  What I imagine you are looking to do is simply refresh the data.  Once the Query Table has been added to your worksheet, you can simply run this code to refresh the data:

Sub RefreshQueryTable()

    ActiveSheet.QueryTables("tobtc?currency=USD&value=1_1").Refresh

End Sub

Keep in mind, if you are using a keyboard shortcut, a user might invoke the shortcut from any sheet in the workbook, thus this code will fail if the user is not on the sheet that contains the Query Table.  You'd want to make sure you explicitly refer to the appropriate sheet:

Sub RefreshQueryTable()
    ThisWorkbook.Sheets("Sheet1").QueryTables("tobtc?currency=USD&value=1_1").Refresh
End Sub


问:
BigQuery: Convert accented characters to their plain ascii equivalents
I have the following string:

```<code>brasília
</code>```

And I need to convert to:

```<code>brasilia
</code>```

Withou the ´ accent!

How can I do on BigQuery?

Thank you!

答:
You can call REPLACE() or REGEXP_REPLACE(). You can find some regular expressions at Remove accents/diacritics in a string in JavaScript.

Alternatively, you can use javascript UDF, but I expect it to be slower.

Body:
I have the following string:

brasília

And I need to convert to:

brasilia

Withou the ´ accent!

How can I do on BigQuery?

Thank you!


问:
Displaying two fields in lookup
Introduction first, question at the end. Please read carefully!

I have a master-detail relation between two tables:

```<code>CREATE TABLE [dbo].[LookupAttributes] (
    [Id] int IDENTITY (1, 1) NOT NULL,
    [Name] nvarchar (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ;
ALTER TABLE [dbo].[LookupAttributes] ADD CONSTRAINT [PK_LookupAttributes] PRIMARY KEY ([Identity]) ;

CREATE TABLE [dbo].[Lookup] (
    [Id] int IDENTITY (1, 1) NOT NULL,
    [LookupAttributesLink] int NOT NULL,
    [Code] nvarchar (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Value] nvarchar (80) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ;
ALTER TABLE [dbo].[Lookup] ADD CONSTRAINT [IX_Lookup] UNIQUE ([LookupAttributenLink], [Code]) ;
</code>```

(There are more fields and indices in both tables but these are the ones that matter...)

The project I'm working on is meant to maintain data in 50+ tables, and every week this data is exported to XML to be used by some desktop application as source data. While I wanted to make this a pretty-looking application, it just needed to be done fast, thus I use a Dynamic Data Site so the data can be maintained. It works just fine, except for this table...

As it turns out, there are 600 different lookup records that share the same code, but different attributes. The DDS displays attribute and code correctly in the list of lookup records so there never was any confusion about which lookup record someone was editing. And this has been in use for over 2 years now.

Now the problem: A new table "Lookup-Override" has been added which links to the [Id] field of the Lookup table. Each record in this new table thus displays the [Code] field, but since [Code] isn't unique, it's unclear which Override record belongs to which Lookup record.

To solve this, I need to display more information from the Lookup record. Since the only unique set of fields is the attribute plus code, I need to display both. But displaying [LookupAttributesLink]+[Code] isn't an option either, since [LookupAttributesLink] is just a number.
I need the DDS to display [Attributes].[LookupAttributesLink]+[Lookup].[Code] in a single column. Question is: how?
I've considered adding a calculated field to the Lookup table, but I cannot get the attribute name that way.
I could create a special page to maintain this table but I don't like that solution either, since it "breaks" the DDS principle in my opinion. I'm trying to avoid such pages.
So, any other possibilities to get the site display both attribute name and lookup code in the override table?

The most interesting solution would be by using a calculated field which could retrieve the attribute name. How to do that?

Solved it myself! See answer below, which works just fine.

答:
Found it! I had to do a few things:

```<code>CREATE FUNCTION LookupName (
  @Attr int,
  @Code nvarchar(255)
) RETURNS nvarchar(1000)
AS
BEGIN
 DECLARE @Name nvarchar(1000)
 SELECT @Name = Name
 FROM [dbo].[LookupAttributes]
 WHERE [Id]=@Attr;
 RETURN @Name + '/' + @Code;
END
GO
ALTER TABLE [dbo].[lookup] ADD [Name] AS [dbo].[LookupName]([LookupAttributesLink], [Code])
GO
</code>```

This will add an additional calculated field to the table which uses a function to calculate the proper name. I then had to add some metadata for the lookup table:

```<code>[MetadataType(typeof(LookupMetadata))]
public partial class Lookup { }
[DisplayColumn("Name", "Name")]
[DisplayName("Lookup")]
public class LookupMetadata
{
    [ScaffoldColumn(false)]
    public int Id;
    [ScaffoldColumn(false)]
    public object Name;
}
</code>```

This will hide the Name column from the Lookup table itself, but it makes it visible for the Override table. (And it will be used to display the proper value.

Done this, solved the problem! Quite easy, actually. :-)

Title: Displaying two fields in lookup

Body:
Introduction first, question at the end. Please read carefully!

I have a master-detail relation between two tables:

CREATE TABLE [dbo].[LookupAttributes] (
    [Id] int IDENTITY (1, 1) NOT NULL,
    [Name] nvarchar (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ;
ALTER TABLE [dbo].[LookupAttributes] ADD CONSTRAINT [PK_LookupAttributes] PRIMARY KEY ([Identity]) ;

CREATE TABLE [dbo].[Lookup] (
    [Id] int IDENTITY (1, 1) NOT NULL,
    [LookupAttributesLink] int NOT NULL,
    [Code] nvarchar (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Value] nvarchar (80) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ;
ALTER TABLE [dbo].[Lookup] ADD CONSTRAINT [IX_Lookup] UNIQUE ([LookupAttributenLink], [Code]) ;

(There are more fields and indices in both tables but these are the ones that matter...)

The project I'm working on is meant to maintain data in 50+ tables, and every week this data is exported to XML to be used by some desktop application as source data. While I wanted to make this a pretty-looking application, it just needed to be done fast, thus I use a Dynamic Data Site so the data can be maintained. It works just fine, except for this table...

As it turns out, there are 600 different lookup records that share the same code, but different attributes. The DDS displays attribute and code correctly in the list of lookup records so there never was any confusion about which lookup record someone was editing. And this has been in use for over 2 years now.

Now the problem: A new table "Lookup-Override" has been added which links to the [Id] field of the Lookup table. Each record in this new table thus displays the [Code] field, but since [Code] isn't unique, it's unclear which Override record belongs to which Lookup record.

To solve this, I need to display more information from the Lookup record. Since the only unique set of fields is the attribute plus code, I need to display both. But displaying [LookupAttributesLink]+[Code] isn't an option either, since [LookupAttributesLink] is just a number.
I need the DDS to display [Attributes].[LookupAttributesLink]+[Lookup].[Code] in a single column. Question is: how?
I've considered adding a calculated field to the Lookup table, but I cannot get the attribute name that way.
I could create a special page to maintain this table but I don't like that solution either, since it "breaks" the DDS principle in my opinion. I'm trying to avoid such pages.
So, any other possibilities to get the site display both attribute name and lookup code in the override table?

The most interesting solution would be by using a calculated field which could retrieve the attribute name. How to do that?

Solved it myself! See answer below, which works just fine.

Body:
Found it! I had to do a few things:

CREATE FUNCTION LookupName (
  @Attr int,
  @Code nvarchar(255)
) RETURNS nvarchar(1000)
AS
BEGIN
 DECLARE @Name nvarchar(1000)
 SELECT @Name = Name
 FROM [dbo].[LookupAttributes]
 WHERE [Id]=@Attr;
 RETURN @Name + '/' + @Code;
END
GO
ALTER TABLE [dbo].[lookup] ADD [Name] AS [dbo].[LookupName]([LookupAttributesLink], [Code])
GO

This will add an additional calculated field to the table which uses a function to calculate the proper name. I then had to add some metadata for the lookup table:

[MetadataType(typeof(LookupMetadata))]
public partial class Lookup { }
[DisplayColumn("Name", "Name")]
[DisplayName("Lookup")]
public class LookupMetadata
{
    [ScaffoldColumn(false)]
    public int Id;
    [ScaffoldColumn(false)]
    public object Name;
}

This will hide the Name column from the Lookup table itself, but it makes it visible for the Override table. (And it will be used to display the proper value.

Done this, solved the problem! Quite easy, actually. :-)


问:
Bigdata Live data streaming using flume
I am trying to analyze twitter data using flume
i got the files from twitter using flume in BigInsights
but the data I received  is of compressed Avro schema which is not readable
can anyone tell me a way so that  can convert that file to JSON (Readable)
in order to do some analysis on it.

Or is there any way so that the data I receive is already in JSON (Readable) format.

Thanks In Advance.

This is the data i received

答:
Avro format is not designed to be human readable and it's desinged to be consumed by programs. But you have a few options to view this data or even better analyze the data.

Create Hive Table: This option will allow you to analyze data using SQL queries, Spark SQL, Spark notebooks, visualization tools like Tableau and Excel too.
Your table creation script will look like this:

```<code>CREATE TABLE twitter_data
ROW FORMAT
SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS
INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
TBLPROPERTIES ('avro.schema.literal'='{...
</code>```

In schema literal, you can define your own schema too.

Write Program: If you are developer and want to/like to wrangle data using programming, you have many languages to choose from to read, parse, convert and write from Avro file to JSON.

Title: Bigdata Live data streaming using flume

Body:
Avro format is not designed to be human readable and it's desinged to be consumed by programs. But you have a few options to view this data or even better analyze the data.

Create Hive Table: This option will allow you to analyze data using SQL queries, Spark SQL, Spark notebooks, visualization tools like Tableau and Excel too.
Your table creation script will look like this:

CREATE TABLE twitter_data
ROW FORMAT
SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS
INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
TBLPROPERTIES ('avro.schema.literal'='{...

In schema literal, you can define your own schema too.

Write Program: If you are developer and want to/like to wrangle data using programming, you have many languages to choose from to read, parse, convert and write from Avro file to JSON.


问:
Unit testing elixir functions properly
I'm fairly new to elixir and functional programming in general and I'm struggling to properly unit test functions that are composed of other functions. The general question is: when I have a function f that uses other functions g, h... internally, which approach should I take to test the whole?

Coming from the OOP world the first approach that comes to mind involves injecting the functions f depends of. I could unit test g, h... and inject all of those as arguments to f. Then, unit tests for f would just make sure it calls the injected functions as expected. This feels like overfitting though, and as an overall cumbersome approach that is against the functional mindset for which function composition should be a cheap thing to do and you should not be concerning yourself on passing all those arguments around the whole codebase.

I can also unit test g, h... as well as f by treating each of those as black boxes, which feels like the appropriate thing to do, but then the complexity of f's tests increases dramatically. Having simple tests that scale is one of the main purposes of unit testing.

To make the argument more concrete I'll put an example of a function that composes other functions inside and that I don't know how to unit test properly. This in particular is code for a plug that handles the creation of a resource in a RESTful fashion. Note that some of the "dependencies" are pure functions (such as validate_account_admin) but others are not (Providers.create):

  def call(conn, _opts) do
    account_uuid = conn.assigns.current_user.account["uuid"]

    with {:ok, conn}      <- Http.Authorization.validate_account_admin(conn),
         {:ok, form_data} <- Http.coerce_form_data(conn, FormData),
         {:ok, provider}  <- Providers.create(FormData.to_provider(form_data), account_uuid: account_uuid) do
      Http.respond_create(conn, Http.provider_path(provider))
    else
      {:error, reason, messages} -> Http.handle_error(conn, reason, messages)
    end
  end
```

Thanks!

答:
Maybe this will be quite subjective answer, because there might be no perfect and ultimate one for such question.

Your assumption for me is wrong in terms of using public functions inside other public function. You shouldn't do that at all in business logic areas, because they should be separated and the only place where you can do that and - in fact - you has to is in controllers, but you test controllers with integration tests, not with unit tests, so all you care in such tests are proper and valid responses.

I like Erlang's explicit approach to declare which functions should be public by using export clause. In Elixir you should also follow this approach and whatever should be hidden in the module, should be declared with defp and defmacrop respectively for private functions and private macros.

Your unit tests should follow the rule of black box - you care about the output based on the input. That's all. Test is dumb and doesn't know at all how function under test looks like and what it contains.

In your example you're using some functions in the Plug callfunction and I'm pretty sure that this plug makes more than it should - remember about single responsible principle. This makes this one function almost impossible to test without mocking... I would rewrite this plug into 3 or 4 four separated plugs, because with clause is redundant - plugs check the outcom of previous plug to proceed - it's case inside case, just what with does.

Considering you have new plugs you can use some extra functions inside the plug except call and init that do the real work defined as private functions and this action would propably help you organize your code and avoid creating chained modules in terms of usage and responsibility.

Then, unit tests would be much easier, because you would test isolated plugs.

Assuming that you have this plug called like this:

```<code>plug MyPlug
</code>```

you would rewrite into:

```<code>plug :validate_is_admin
plug :coerce_form_data
plug :create_from_form_data
</code>```

Maybe it's simplified, but I hope you get what I meant here.

TL; DR: Split functions into smaller ones and test them in isolation. Hide internal computations in private functions and test only public API.

Title: Unit testing elixir functions properly

Body:
I'm fairly new to elixir and functional programming in general and I'm struggling to properly unit test functions that are composed of other functions. The general question is: when I have a function f that uses other functions g, h... internally, which approach should I take to test the whole?

Coming from the OOP world the first approach that comes to mind involves injecting the functions f depends of. I could unit test g, h... and inject all of those as arguments to f. Then, unit tests for f would just make sure it calls the injected functions as expected. This feels like overfitting though, and as an overall cumbersome approach that is against the functional mindset for which function composition should be a cheap thing to do and you should not be concerning yourself on passing all those arguments around the whole codebase.

I can also unit test g, h... as well as f by treating each of those as black boxes, which feels like the appropriate thing to do, but then the complexity of f's tests increases dramatically. Having simple tests that scale is one of the main purposes of unit testing.

To make the argument more concrete I'll put an example of a function that composes other functions inside and that I don't know how to unit test properly. This in particular is code for a plug that handles the creation of a resource in a RESTful fashion. Note that some of the "dependencies" are pure functions (such as validate_account_admin) but others are not (Providers.create):

  def call(conn, _opts) do
    account_uuid = conn.assigns.current_user.account["uuid"]

    with {:ok, conn}      <- Http.Authorization.validate_account_admin(conn),
         {:ok, form_data} <- Http.coerce_form_data(conn, FormData),
         {:ok, provider}  <- Providers.create(FormData.to_provider(form_data), account_uuid: account_uuid) do
      Http.respond_create(conn, Http.provider_path(provider))
    else
      {:error, reason, messages} -> Http.handle_error(conn, reason, messages)
    end
  end

Thanks!

Body:
Maybe this will be quite subjective answer, because there might be no perfect and ultimate one for such question.

Your assumption for me is wrong in terms of using public functions inside other public function. You shouldn't do that at all in business logic areas, because they should be separated and the only place where you can do that and - in fact - you has to is in controllers, but you test controllers with integration tests, not with unit tests, so all you care in such tests are proper and valid responses.

I like Erlang's explicit approach to declare which functions should be public by using export clause. In Elixir you should also follow this approach and whatever should be hidden in the module, should be declared with defp and defmacrop respectively for private functions and private macros.

Your unit tests should follow the rule of black box - you care about the output based on the input. That's all. Test is dumb and doesn't know at all how function under test looks like and what it contains.

In your example you're using some functions in the Plug callfunction and I'm pretty sure that this plug makes more than it should - remember about single responsible principle. This makes this one function almost impossible to test without mocking... I would rewrite this plug into 3 or 4 four separated plugs, because with clause is redundant - plugs check the outcom of previous plug to proceed - it's case inside case, just what with does.

Considering you have new plugs you can use some extra functions inside the plug except call and init that do the real work defined as private functions and this action would propably help you organize your code and avoid creating chained modules in terms of usage and responsibility.

Then, unit tests would be much easier, because you would test isolated plugs.

Assuming that you have this plug called like this:

plug MyPlug

you would rewrite into:

plug :validate_is_admin
plug :coerce_form_data
plug :create_from_form_data

Maybe it's simplified, but I hope you get what I meant here.

TL; DR: Split functions into smaller ones and test them in isolation. Hide internal computations in private functions and test only public API.


问:
express error: "TypeError('Router.use() requires middleware
Brand new to Node and following along with thisMEAN app tutorial and encountering an error when executing 'node server' in CL in Linux (I've been using sudo to mkdir and touch all the files, and run the node server).  .

```<code>  >sudo node server
/home/jake/web/tasker/node_modules/express/lib/router/index.js:458
  throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
  ^

TypeError: Router.use() requires middleware function but got a Object
at Function.use         (/home/jake/web/tasker/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/home/jake/web/tasker/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/home/jake/web/tasker/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/home/jake/web/tasker/server.js:23:5)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
</code>```

My main server.js file:

```<code>var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
//static folder for Angular stuff
app.use(express.static(path.join(__dirname, 'client')));
//body Parser MiddleWare
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', tasks);
app.listen(port, function(){
console.log('Server has begun');
});
</code>```

and package.json:

```<code>{
  "name": "tasker",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.1",
   "ejs": "^2.5.6",
    "express": "^4.15.2",
    "mongojs": "^2.4.0"
  }
}
</code>```

答: I ended up redoing the tutorial, except instead of creating the folders and files via command line, I just used right-click, and now it works. So it could've been related to sudo permissions, or I simply didn't write the wrong thing my second time doing  it. Sorry for the non-answer.</p>

Body:
Brand new to Node and following along with thisMEAN app tutorial and encountering an error when executing 'node server' in CL in Linux (I've been using sudo to mkdir and touch all the files, and run the node server).  .

  >sudo node server
/home/jake/web/tasker/node_modules/express/lib/router/index.js:458
  throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
  ^

TypeError: Router.use() requires middleware function but got a Object
at Function.use         (/home/jake/web/tasker/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/home/jake/web/tasker/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/home/jake/web/tasker/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/home/jake/web/tasker/server.js:23:5)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)

My main server.js file:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
//static folder for Angular stuff
app.use(express.static(path.join(__dirname, 'client')));
//body Parser MiddleWare
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', tasks);
app.listen(port, function(){
console.log('Server has begun');
});

and package.json:

{
  "name": "tasker",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.1",
   "ejs": "^2.5.6",
    "express": "^4.15.2",
    "mongojs": "^2.4.0"
  }
}


答: Currently, the iOS SDK does not support redirecting incoming calls from the system to a custom application. There is only support for initiating a call.</p>

Title: Build Application to Answer Phone Call and Delegate To iPhone's Phone Application

Body:
We want to build an application that the user can interact with while taking a phone call.  The idea is that the user can do voice communication using the phone application of the iPhone and at the same time use our application to type and send additional data that is relevant to the call such as an e-mail address.  This is the scenario:

User get's a call on the iPhone

The user clicks a button on our app to answer the call and let the phone application on the iPhone handle the phone call in the background.

Our application continues to run in the foreground so that the user can interact with our application to type and send data such as an e-mail address that is relevant to the call.

Is there a way for our application to answer an incoming phone call and let the phone application of the iPhone handle the call in the background while our application continues to run in the foreground?

Thanks,
Prasanna


问:
How to use groupby/Lambda
```<code>public class Emp {

    public String name;
    public String department;
    public double salary;

    public Emp(String name, String department, double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}
</code>```

So I am trying to get top 5 departments by summing salaries and

Also trying to top 5 employees in a department say sales

How do I use groupBy in java 8 and then summing and sorting

This is the data I have

Emp("Michael", "Sales",20000.0)
 Emp("Jean","Marketing",250000.0)
 Emp("Jason","Biz-dev",220000.0)
 ..........

答:
Top 5 departments by total of salaries:

```<code>List<String> top5Departments = employees.stream()
    .collect(Collectors.groupingBy(e -> e.department,
                 Collectors.summingDouble(e -> e.salary)))
    .entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .limit(5)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());
</code>```

Top 5 employees by salary in a specific department:

```<code>List<Emp> top5SalesEmployees = employees.stream()
    .filter(e -> "sales".equals(e.department))
    .sorted(Comparator.comparingDouble(e -> e.salary).reversed())
    .limit(5)
    .collect(Collectors.toList());
</code>```

Title: How to use groupby/Lambda

Body:
public class Emp {

    public String name;
    public String department;
    public double salary;

    public Emp(String name, String department, double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}

So I am trying to get top 5 departments by summing salaries and

Also trying to top 5 employees in a department say sales

How do I use groupBy in java 8 and then summing and sorting

This is the data I have

Emp("Michael", "Sales",20000.0)
 Emp("Jean","Marketing",250000.0)
 Emp("Jason","Biz-dev",220000.0)
 ..........

Body:
Top 5 departments by total of salaries:

List<String> top5Departments = employees.stream()
    .collect(Collectors.groupingBy(e -> e.department,
                 Collectors.summingDouble(e -> e.salary)))
    .entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .limit(5)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

Top 5 employees by salary in a specific department:

List<Emp> top5SalesEmployees = employees.stream()
    .filter(e -> "sales".equals(e.department))
    .sorted(Comparator.comparingDouble(e -> e.salary).reversed())
    .limit(5)
    .collect(Collectors.toList());


问:
VS2017: The debugger is not properly installed. Cannot debug the requested type of code
I installed Visual Studio 2017 Enterprise edition and when I am running my application getting the below error.

答:
Install Visual Studio 2015 Professional.

I really wish this was not the answer, but it was the only way I got around the debugger not installed problem.


问:
The correct way to manage cocoa memory when working with Objective-C from Rust
I'm struggling with one issue related to the cocoa foundation memory management. Basically I have a project, written in Rust and I'm using cocoa-rs and objc-rs to interact with Objective-C. I'm familiar with memory management in CoreFoundation and CocoaFoundation (I've already read the corresponding articles in documentation). I did not have any memory issues when I worked with CoreFoundation functions, but I'm having a lot of problems when I use CocoaFoundation related stuff, it seems that getting any objects from CocoaFoundation leaks memory.

Here is the simplified version of one of the functions which leads to a memory memory:

```<code>pub fn enumerate_apps()-> Vec<Rc<AppInfo>> {
    let mut apps_list = Vec::new();
    unsafe {
        let shared_workspace: *mut Object = msg_send![class("NSWorkspace"), sharedWorkspace];
        let running_apps: *mut Object = msg_send![shared_workspace, runningApplications];

        let apps_count = msg_send![running_apps, count];
        for i in 0..apps_count {
            let app: *mut Object = msg_send![running_apps, objectAtIndex:i];

            // Those ones are not used at the moment, but I actually need them,
            // I just removed all business logic to keep the example simple and compilable
            // to demonstrate the problem.
            let bundle_url: *mut Object = msg_send![app, bundleURL];
            let app_bundle: *mut Object = msg_send![class("NSBundle"), bundleWithURL:bundle_url];
            let info_dict: *mut Object = msg_send![app_bundle, infoDictionary];

            apps_list.push(Rc::new(AppInfo {
                pid: msg_send![app, processIdentifier],
            }));
        }
    }
    apps_list
}
</code>```

I tried to call this function inside a loop to make the memory leak visible:

```<code>fn main() {
    loop {
        for i in 0..200 {
            enumerate_apps();
        }
        std::thread::sleep(std::time::Duration::from_millis(5000));
    }
}
</code>```

When I run the application, I can see that it consumes more and more memory over time.

My question is: why? What is the correct way to manage memory in a such FFI code? If I run the same code in XCode, using the plain Objective-C, it works fine and seems that it does not leak memory. Well, the reason why the memory is not leaked in XCode is that ARC is enabled by default. To my knowledge ARC is not enabled when we work with Objective-C from Rust in a such manner, so basically it means that we have to manage memory ourselves. Commenting 3 lines containing bundle_url, app_bundle, info_dict creates an illusion that the memory leak is gone (without commenting them, the process leaks a couple megabytes of memory every 2 seconds), but actually the memory is still leaked, but not that fast.

What I tried:

I tried to create an NSAutoreleasePool in the beginning of the function and call autorelease() for bundle_url and app_bundle upon creation. Did not help, the memory it still leaked.

I tried to call release() manually on bundle_url and app_bundle, did not have any effect.

Even tried to call dealloc() on them (which I believe is a wrong way), which also did not help to solve my problem.

Am I doing something wrong? Or is it a bug in objc-rs (I guess this is very unlikely, but who knows)?

答:
Since Objective-C ARC is not implemented in objc-rs/cocoa-rs, you need to follow the memory management rule, in particular for this question: You must not relinquish ownership of an object you do not own.  That is you should not call autorelease(), release() or dealloc() on any of the returned objects.

What you should do is to create an NSAutoreleasePool inside the function, and don't touch anything else. The pool will free all those objects when it is released.

```<code>pub fn enumerate_apps()-> Vec<Rc<AppInfo>> {
    let mut apps_list = Vec::new();
    unsafe {
        let autoreleasePool: *mut Object = msg_send![class("NSAutoreleasePool"), new];

        // ...
        // all code unchanged
        // ...

        msg_send![autoreleasePool, release];
    }
    apps_list
}
</code>```

Why calling autorelease()/release()/dealloc() on bundle_url/app_bundle/info_dict cannot decrease memory? Because it is not just these objects leaking memory. The biggest consumption is the running_apps object.

And why explicitly calling autorelease()/release()/dealloc() is wrong? Let's review the ObjC memory management rules, and compare it with normal Rust code (I assume you know how the Rc<T> type works):

You own any object you create — You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”

You could think of it like:

```<code>// Objective-C code:
NSMutableString* s = [NSMutableString new];
NSMutableString* t = [s mutableCopy];

// Similar to this in Rust:
let s: Rc<NSMutableString> = Rc::new(NSMutableString::new());
let t: Rc<NSMutableString> = Rc::new(s.mutableCopy());
</code>```

Your code never called any method begins with "alloc", "new", "copy" or "mutableCopy", so you don't own any of them. This naming convention is followed by all ObjC APIs.

You can take ownership of an object using retain.

This is similar to having an object a: Rc<T>, and then you get a new reference by calling b = Rc::clone(&a). Now b also "owns" the original object through reference-counting:

```<code>// Objective-C code:
NSMutableString* u = [t retain];

// Similar to this in Rust:
let u: Rc<NSMutableString> = Rc::clone(&u);
</code>```

But you never called retain, so still you don't own any objects.

When you no longer need it, you must relinquish ownership of an object you own — You relinquish ownership of an object by sending it a release message or an autorelease message.

In terms of Rust, sending a -release message is equivalent to dropping the Rc object.

```<code>// Objective-C code:
[u release];

// Similar to this in Rust:
drop(u);
</code>```

-autorelease transfers the ownership to the autorelease pool. The most recently allocated NSAutoreleasePool will be found, the ownership of the object be moved into that pool, and we only keep a borrowed reference(*).

```<code>// Objective-C code:
NSMutableString* v = [t autorelease];

// Similar to this in Rust:
let pool: &NSAutoreleasePool = find_top_autorelease_pool()?;
let v: &NSMutableString = pool.add_object(t);
// `t` is passed-by-value, so `pool` now owns `t`.
// `pool` returns a borrowed reference,
// so that we can still access the memory pointed to by `t`,
// but we no longer own it.
</code>```

You must not relinquish ownership of an object you do not own.

That is you can never drop the memory through a borrowed reference. Well in Rust it is impossible but Objective-C doesn't have a borrow checker.

Additionally, calling -dealloc is like explicitly invoking the destructor via drop(*s) in Rust. This bypasses the reference-counting mechanism and is explicitly discouraged.

Let's recap:

None of the methods you called (sharedWorkspace/runningApplications/objectAtIndex:/bundleURL/bundleWithURL:/infoDictionary) begins with alloc/new/copy/mutableCopy.

You never called -retain.

That means everything you've got are borrowed, by rules 1 and 2.

That means you should never call release() or autorelease(), by rule 4.

Calling -release or -autorelease on objects you don't own result in double-free. This may cause SEGFAULT, or no-op, or any undefined behavior.

Why the program leaks like a sieve if we don't provide an NSAutoreleasePool? The runningApplications/bundleWithURL: methods do allocate objects, but adhering to the Cocoa memory management rule, they call -autorelease internally to ensure you don't get owned objects. But if we don't allocate any pools, -autorelease can transfer the ownership to nowhere, i.e. those auto-released objects become unowned by anyone, and nobody has the ownership to free them, and thus leaked.

(*): The analogy is not perfect, because you could get a new ownership with [[x autorelease] retain]. But this detail doesn't matter here.

Body:
I'm struggling with one issue related to the cocoa foundation memory management. Basically I have a project, written in Rust and I'm using cocoa-rs and objc-rs to interact with Objective-C. I'm familiar with memory management in CoreFoundation and CocoaFoundation (I've already read the corresponding articles in documentation). I did not have any memory issues when I worked with CoreFoundation functions, but I'm having a lot of problems when I use CocoaFoundation related stuff, it seems that getting any objects from CocoaFoundation leaks memory.

Here is the simplified version of one of the functions which leads to a memory memory:

pub fn enumerate_apps()-> Vec<Rc<AppInfo>> {
    let mut apps_list = Vec::new();
    unsafe {
        let shared_workspace: *mut Object = msg_send![class("NSWorkspace"), sharedWorkspace];
        let running_apps: *mut Object = msg_send![shared_workspace, runningApplications];

        let apps_count = msg_send![running_apps, count];
        for i in 0..apps_count {
            let app: *mut Object = msg_send![running_apps, objectAtIndex:i];

            // Those ones are not used at the moment, but I actually need them,
            // I just removed all business logic to keep the example simple and compilable
            // to demonstrate the problem.
            let bundle_url: *mut Object = msg_send![app, bundleURL];
            let app_bundle: *mut Object = msg_send![class("NSBundle"), bundleWithURL:bundle_url];
            let info_dict: *mut Object = msg_send![app_bundle, infoDictionary];

            apps_list.push(Rc::new(AppInfo {
                pid: msg_send![app, processIdentifier],
            }));
        }
    }
    apps_list
}

I tried to call this function inside a loop to make the memory leak visible:

fn main() {
    loop {
        for i in 0..200 {
            enumerate_apps();
        }
        std::thread::sleep(std::time::Duration::from_millis(5000));
    }
}

When I run the application, I can see that it consumes more and more memory over time.

My question is: why? What is the correct way to manage memory in a such FFI code? If I run the same code in XCode, using the plain Objective-C, it works fine and seems that it does not leak memory. Well, the reason why the memory is not leaked in XCode is that ARC is enabled by default. To my knowledge ARC is not enabled when we work with Objective-C from Rust in a such manner, so basically it means that we have to manage memory ourselves. Commenting 3 lines containing bundle_url, app_bundle, info_dict creates an illusion that the memory leak is gone (without commenting them, the process leaks a couple megabytes of memory every 2 seconds), but actually the memory is still leaked, but not that fast.

What I tried:

I tried to create an NSAutoreleasePool in the beginning of the function and call autorelease() for bundle_url and app_bundle upon creation. Did not help, the memory it still leaked.

I tried to call release() manually on bundle_url and app_bundle, did not have any effect.

Even tried to call dealloc() on them (which I believe is a wrong way), which also did not help to solve my problem.

Am I doing something wrong? Or is it a bug in objc-rs (I guess this is very unlikely, but who knows)?

Body:
Since Objective-C ARC is not implemented in objc-rs/cocoa-rs, you need to follow the memory management rule, in particular for this question: You must not relinquish ownership of an object you do not own.  That is you should not call autorelease(), release() or dealloc() on any of the returned objects.

What you should do is to create an NSAutoreleasePool inside the function, and don't touch anything else. The pool will free all those objects when it is released.

pub fn enumerate_apps()-> Vec<Rc<AppInfo>> {
    let mut apps_list = Vec::new();
    unsafe {
        let autoreleasePool: *mut Object = msg_send![class("NSAutoreleasePool"), new];

        // ...
        // all code unchanged
        // ...

        msg_send![autoreleasePool, release];
    }
    apps_list
}

Why calling autorelease()/release()/dealloc() on bundle_url/app_bundle/info_dict cannot decrease memory? Because it is not just these objects leaking memory. The biggest consumption is the running_apps object.

And why explicitly calling autorelease()/release()/dealloc() is wrong? Let's review the ObjC memory management rules, and compare it with normal Rust code (I assume you know how the Rc<T> type works):

You own any object you create — You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”

You could think of it like:

// Objective-C code:
NSMutableString* s = [NSMutableString new];
NSMutableString* t = [s mutableCopy];

// Similar to this in Rust:
let s: Rc<NSMutableString> = Rc::new(NSMutableString::new());
let t: Rc<NSMutableString> = Rc::new(s.mutableCopy());

Your code never called any method begins with "alloc", "new", "copy" or "mutableCopy", so you don't own any of them. This naming convention is followed by all ObjC APIs.

You can take ownership of an object using retain.

This is similar to having an object a: Rc<T>, and then you get a new reference by calling b = Rc::clone(&a). Now b also "owns" the original object through reference-counting:

// Objective-C code:
NSMutableString* u = [t retain];

// Similar to this in Rust:
let u: Rc<NSMutableString> = Rc::clone(&u);

But you never called retain, so still you don't own any objects.

When you no longer need it, you must relinquish ownership of an object you own — You relinquish ownership of an object by sending it a release message or an autorelease message.

In terms of Rust, sending a -release message is equivalent to dropping the Rc object.

// Objective-C code:
[u release];

// Similar to this in Rust:
drop(u);

-autorelease transfers the ownership to the autorelease pool. The most recently allocated NSAutoreleasePool will be found, the ownership of the object be moved into that pool, and we only keep a borrowed reference(*).

// Objective-C code:
NSMutableString* v = [t autorelease];

// Similar to this in Rust:
let pool: &NSAutoreleasePool = find_top_autorelease_pool()?;
let v: &NSMutableString = pool.add_object(t);
// `t` is passed-by-value, so `pool` now owns `t`.
// `pool` returns a borrowed reference,
// so that we can still access the memory pointed to by `t`,
// but we no longer own it.

You must not relinquish ownership of an object you do not own.

That is you can never drop the memory through a borrowed reference. Well in Rust it is impossible but Objective-C doesn't have a borrow checker.

Additionally, calling -dealloc is like explicitly invoking the destructor via drop(*s) in Rust. This bypasses the reference-counting mechanism and is explicitly discouraged.

Let's recap:

None of the methods you called (sharedWorkspace/runningApplications/objectAtIndex:/bundleURL/bundleWithURL:/infoDictionary) begins with alloc/new/copy/mutableCopy.

You never called -retain.

That means everything you've got are borrowed, by rules 1 and 2.

That means you should never call release() or autorelease(), by rule 4.

Calling -release or -autorelease on objects you don't own result in double-free. This may cause SEGFAULT, or no-op, or any undefined behavior.

Why the program leaks like a sieve if we don't provide an NSAutoreleasePool? The runningApplications/bundleWithURL: methods do allocate objects, but adhering to the Cocoa memory management rule, they call -autorelease internally to ensure you don't get owned objects. But if we don't allocate any pools, -autorelease can transfer the ownership to nowhere, i.e. those auto-released objects become unowned by anyone, and nobody has the ownership to free them, and thus leaked.

(*): The analogy is not perfect, because you could get a new ownership with [[x autorelease] retain]. But this detail doesn't matter here.


问:
Wordpress: How can I pick plugins directory in my javascript file?
I need to access plugins directory in my customer javascript file. I know we have do have functions to retrieve plugins directory path using php function plugins_url().

However, I need this to retrieve in my js file where I have to put some images.

Any ideas??

PS: My js file is saved as a javascript file and therefore, I can't use php tags in it

答:
It's actually quite easy...
In functions.php

wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main.js', array('jquery'), '20151215', true );

$translation_array = array( 'templateUrl' =>get_stylesheet_directory_uri() );       //after wp_enqueue_script

wp_localize_script( 'main', 'jsVars', $translation_array );

then in the js-file:

```<code>var sitepath=jsVars.templateUrl+"/";
</code>```

Edit: Just in case it's not understood completely:
The translation array is created and contains a key value pair
The array is then injected as jsVars (javascript variable) into the js scripts
So basically we (mis)use the translation array to inject variables to JS
with the wp_localize_script command.
off course instead of the templateUrl you can define all the params you want with PHP to inject their values into any js file you want.
In this example we inject the template Url into the main js script via jsVars, but it can be any variable into any js script

Body:
It's actually quite easy...
In functions.php

wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main.js', array('jquery'), '20151215', true );

$translation_array = array( 'templateUrl' =>get_stylesheet_directory_uri() );       //after wp_enqueue_script

wp_localize_script( 'main', 'jsVars', $translation_array );

then in the js-file:

var sitepath=jsVars.templateUrl+"/";

Edit: Just in case it's not understood completely:
The translation array is created and contains a key value pair
The array is then injected as jsVars (javascript variable) into the js scripts
So basically we (mis)use the translation array to inject variables to JS
with the wp_localize_script command.
off course instead of the templateUrl you can define all the params you want with PHP to inject their values into any js file you want.
In this example we inject the template Url into the main js script via jsVars, but it can be any variable into any js script

ContentLicense: CC BY-SA 4.0


问:
How do I make DOM/event listeners aware of newly appended nodes?
TL;DR:

I use $(..).append(node), but newly added nodes are not considered for inclusion despite them (supposedly) matching jQuery selectors.

Question

I have some code below that uses checkboxes but emulates radio button behavior.  In other words, only one checkbox can (validly) be selected at any time.  No more than one should be selected.

If you run the example below and click on the first 3 checkboxes, they will behave like radio buttons.  Only one will be selected, no matter how many you click.

However, if you Add Point, newly added points will not be considered for the JS even though in theory it should grab them too...

Specifically:  You can select the newly added checkbox, and it will be selected in addition to one already selected previously.  That is incorrect as only 1 should be selected at any time and all others should be unselected.

What is happening and how can I have newly added nodes be included into jQuery selectors?

$(function() {

  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });

  $("#addCasePoint").on("click", function() {
    var newRowIndex = $('#newRowIndex').text();
    var template = $('#casePointTemplate').data('template');
    template = template.replace(/__index__/g, newRowIndex);
    $('#casePointsFieldset').append(template);
    $('#newRowIndex').text(++newRowIndex);
    return false;
  });

  //deletes case point
  $("#selection").on("click", ".removeCase", function() {
    var caseCount = $('#selection .casePointFieldset').length
    if (caseCount === 1) return false; //keep at least one row
    $(this).closest("fieldset").remove();
    return false;
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.casePointFieldset {
  display: inline-block;
}</code>```

<form id="selection">
  <fieldset id="casePointsFieldset">
    <legend>Case Points</legend>

      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>

    <span id="casePointTemplate" data-template="<fieldset class="casePointFieldset">
Duty: <input name="point[__index__]" class="duty" value="1" type="checkbox">
<button class="removeCase">Remove</button></fieldset>">

  </fieldset>

  <button id="addCasePoint">Add Point</button>
</form>```

答:
Easiest way will be, attaching the event to the document. In the past this was done with the live() method.

```<code> $(document).on('click', '.duty', function(event) {
      $("input.duty").prop("checked", false);
      $(this).prop("checked", true);
  });
</code>```

Body:
TL;DR:

I use $(..).append(node), but newly added nodes are not considered for inclusion despite them (supposedly) matching jQuery selectors.

Question

I have some code below that uses checkboxes but emulates radio button behavior.  In other words, only one checkbox can (validly) be selected at any time.  No more than one should be selected.

If you run the example below and click on the first 3 checkboxes, they will behave like radio buttons.  Only one will be selected, no matter how many you click.

However, if you Add Point, newly added points will not be considered for the JS even though in theory it should grab them too...

Specifically:  You can select the newly added checkbox, and it will be selected in addition to one already selected previously.  That is incorrect as only 1 should be selected at any time and all others should be unselected.

What is happening and how can I have newly added nodes be included into jQuery selectors?

$(function() {

  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });

  $("#addCasePoint").on("click", function() {
    var newRowIndex = $('#newRowIndex').text();
    var template = $('#casePointTemplate').data('template');
    template = template.replace(/__index__/g, newRowIndex);
    $('#casePointsFieldset').append(template);
    $('#newRowIndex').text(++newRowIndex);
    return false;
  });

  //deletes case point
  $("#selection").on("click", ".removeCase", function() {
    var caseCount = $('#selection .casePointFieldset').length
    if (caseCount === 1) return false; //keep at least one row
    $(this).closest("fieldset").remove();
    return false;
  });
});

.casePointFieldset {
  display: inline-block;
}

<form id="selection">
  <fieldset id="casePointsFieldset">
    <legend>Case Points</legend>

      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>

    <span id="casePointTemplate" data-template="<fieldset class="casePointFieldset">
Duty: <input name="point[__index__]" class="duty" value="1" type="checkbox">
<button class="removeCase">Remove</button></fieldset>">

  </fieldset>

  <button id="addCasePoint">Add Point</button>
</form>

Body:
Easiest way will be, attaching the event to the document. In the past this was done with the live() method.

 $(document).on('click', '.duty', function(event) {
      $("input.duty").prop("checked", false);
      $(this).prop("checked", true);
  });


问:
Page timing out with 404 error when script runs longer than 120 seconds
I have a script that needs to run for up to 15 minutes through a cron job.  But I can't get the script to stay running.  It errors out with a 404 message at exactly 120 seconds.  Very strange.  I have even called my hosting provider.  I am at a loss.

I have set max_execution_time = 5000

Does anyone have any suggestions?

```<code>set_time_limit(0);

$array = array('1','2', '3');

foreach ($array as $row) {

    echo $row . '<br>';
                 sleep(50);

}
</code>```

答:
You may also need to look at Apache's timeout setting, as you can change the max execution time value in php.ini and still get stopped by Apache's timeout value in the httpd.conf file.

You can find httpd.conf by running httpd -V in terminal (The command name depends on your system/apache version, it can be also apache -V) ~ If you don't have terminal access, you may need to contact your webhost. Example output:

```<code>bash-3.2# httpd -V
Server version: Apache/2.2.22 (Unix)
Server built:   Aug 24 2012 17:16:58
Server's Module Magic Number: 20051115:30
Server loaded:  APR 1.4.5, APR-Util 1.3.12
Compiled using: APR 1.4.5, APR-Util 1.3.12
Architecture:   64-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_FLOCK_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/usr"
 -D SUEXEC_BIN="/usr/bin/suexec"
 -D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/private/var/run/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"     <-- HERE IT IS
</code>```

httpd.conf could look like this: https://www.devside.net/guides/config/linux/httpd-conf

Notice the line:

```<code>Timeout 300
</code>```

Body:
I have a script that needs to run for up to 15 minutes through a cron job.  But I can't get the script to stay running.  It errors out with a 404 message at exactly 120 seconds.  Very strange.  I have even called my hosting provider.  I am at a loss.

I have set max_execution_time = 5000

Does anyone have any suggestions?

set_time_limit(0);

$array = array('1','2', '3');

foreach ($array as $row) {

    echo $row . '
';
                 sleep(50);

}

Body:
You may also need to look at Apache's timeout setting, as you can change the max execution time value in php.ini and still get stopped by Apache's timeout value in the httpd.conf file.

You can find httpd.conf by running httpd -V in terminal (The command name depends on your system/apache version, it can be also apache -V) ~ If you don't have terminal access, you may need to contact your webhost. Example output:

bash-3.2# httpd -V
Server version: Apache/2.2.22 (Unix)
Server built:   Aug 24 2012 17:16:58
Server's Module Magic Number: 20051115:30
Server loaded:  APR 1.4.5, APR-Util 1.3.12
Compiled using: APR 1.4.5, APR-Util 1.3.12
Architecture:   64-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_FLOCK_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/usr"
 -D SUEXEC_BIN="/usr/bin/suexec"
 -D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/private/var/run/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"     <-- HERE IT IS

httpd.conf could look like this: https://www.devside.net/guides/config/linux/httpd-conf

Notice the line:

Timeout 300


问:
Fix UILabel position below UITableViewController's UINavigationBar
We are placing a temporary label over our UITableViewController view when we need to show a status message.  The view goes directly beneath the UINavigationBar.  This works well but the statusView scrolls with the table and will disappear as the table scrolls up.  How can you fix the statusView position even as the table scrolls?

Update:

What almost works as inspired by another question is to use the TableViewDelegate method to fix the statusView position:

```<code>override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}
</code>```

It places our statusView bar in a fixed position but it's partially underneath the navigation bar.   Seems like we just need to tweak the newFrame.origin.y logic....

Update 2:

Per https://stackoverflow.com/a/40202931/47281 just needed to include the status bar:

```<code>    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height
</code>```

答: You can try using a ViewController subclass and add a UITableView to it instead of subclassing UITableViewController.  </p>

Body:
We are placing a temporary label over our UITableViewController view when we need to show a status message.  The view goes directly beneath the UINavigationBar.  This works well but the statusView scrolls with the table and will disappear as the table scrolls up.  How can you fix the statusView position even as the table scrolls?

Update:

What almost works as inspired by another question is to use the TableViewDelegate method to fix the statusView position:

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = statusView.frame
    newFrame.origin.x = 0
    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.bounds.height
    statusView.frame = newFrame
}

It places our statusView bar in a fixed position but it's partially underneath the navigation bar.   Seems like we just need to tweak the newFrame.origin.y logic....

Update 2:

Per https://stackoverflow.com/a/40202931/47281 just needed to include the status bar:

    newFrame.origin.y = self.tableView.contentOffset.y + self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height


问:
github commit information: A commited with B
Can anyone explain why a commit in GitHub would display the following information : 'Contributor-A' committed with 'Contributor-B' on 15 Feb.

Does it mean that 'Contributor-A' is the author (who does not have the push access to the master) and 'Contributor-B' is the committer/maintainer?

Then why isn't there a PR created for merging this commit? Or does it mean that there was a closed PR about this commit, but the maintainer did not merge it via web interface but performed rebase or cherry-picking to include it?

Many thanks!

答:
For sure, it happens when the pull request was merged by "Rebase and Merge" strategy via the web interface, but I'm not sure if this is the unique case.

Contributor-A committed with Contributor-B on 15 Feb.

Contributor-A submitted the pull request and Contributor-B effectively merged it.

It might happen in other scenarios as described here: how to apply a git patch as if the author committed to my repo?


问:
Get specific value from nested collections using LINQ
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

```<code><Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>
</code>```

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

```<code><%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>
</code>```

However this just returns:

```<code>System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String
</code>```

How do I get it to return the actual value I'm after?

答:
try this:

```<code>var val = employees.Where(p => p.ProductId == 454).FirstOrDefault().Benefits.Select(b => b.Value).FirstOrDefault();
</code>```

or

```<code>var benefits_value = employees.Where(p => p.ProductId == 454).Single().Benefits.Select(b => b.Value).Single();
</code>```

Body:
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

<Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

<%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>

However this just returns:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String

How do I get it to return the actual value I'm after?

Body:
try this:

var val = employees.Where(p => p.ProductId == 454).FirstOrDefault().Benefits.Select(b => b.Value).FirstOrDefault();

or

var benefits_value = employees.Where(p => p.ProductId == 454).Single().Benefits.Select(b => b.Value).Single();