问:
Using a constant class to create test descriptions for Testng test description
Our automation framework is written in Java and uses Testng. We use the @Test annotation to mark out our tests and provide the groups and a description for the test which we write in Gherkin. We use the test report created by Serenity

I have been trying to create a static constant class that we can use to build a test description so that it handle HTML tags rather than putting this into the String itself so its easier to read and so any HTML format that the test report uses can be done within this class rather than each

For example:

```<code>@Test( groups = { TestGroup.One, TestGroup.TWO }, description =
                "<b>Given</b> I am in Scenario One</br>" +
                "<b>When</b>I do something</br>" +
                "<b>Then</b>I get a result")
        protected void testScript() {
    ...
    }
</code>```

would actually look like:

```<code>@Test( groups = { TestGroup.One, TestGroup.TWO }, description =
            TestDescription
                .given("I am in Scenario One")
                .when("I do something")
                .then("I get a result");)
    protected void testScript() {
...
}
</code>```

The code I currently have:

```<code>public final class TestDescription {

    private static String description = "";

    public static String given(final String given) {

        return "<b>Given</b>" + given + "</br>";
    }

    public static TestDescription when(final String when) {

        description = description + "<b>When</b>" + when + "</br>";
        return null;
    }

    public static TestDescription then(final String then) {

        description = description + "<b>Then</b>" + then + "</br>";
        return null;
    }

    public static TestDescription and(final String and) {

        description = description + "<b>And</b>" + and + "</br>";
        return null;
    }

    public static String build() {

        return description;
    }
}
</code>```

答:
Annotation attribute values must be compile-time constants in Java. See allowed expressions in Java documentation.

In TestNG the formatting of description attribute can be done through creating a custom TestNG @Test annotation transformer.

Sample code:

```<code>public class MyAnnotationTransformer implements IAnnotationTransformer {

    private static final String GIVEN = "given: ";
    private static final String WHEN = "when: ";
    private static final String THEN = "then: ";

    @Override
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
        if (testMethod != null) {
            String description = annotation.getDescription();
            if (description != null && !description.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String item : description.split("\\|")) {
                    if (item.startsWith(GIVEN)) {
                        sb.append("<b>Given</b> ").append(item.substring(GIVEN.length())).append("<br />");
                    } else if (item.startsWith(WHEN)) {
                        sb.append("<b>When</b> ").append(item.substring(WHEN.length())).append("<br />");
                    } else if (item.startsWith(THEN)) {
                        sb.append("<b>Then</b> ").append(item.substring(THEN.length())).append("<br />");
                    } else {
                        sb.append(item).append("<br />");
                    }
                }
                description = sb.toString();
                annotation.setDescription(description);
            }
        }
    }
}
</code>```

Then the method would be annotated like this:

```<code>@Test( groups = { TestGroup.ONE, TestGroup.TWO }, description =
        "given: I am in Scenario One" +
        "|when: I do something" +
        "|then: I get a result")
protected void testScript() {
    //...
}
</code>```

Note: when implementing custom TestNG listeners, we need to make sure theyare used by TestNG. (Listeners can be specified in the TestNG XML test suite or through other means.)

The resulting description in this case would be:

```<code><b>Given</b> I am in Scenario One<br /><b>When</b> I do something<br /><b>Then</b> I get a result<br />
</code>```

I hope this helps.

Body:
Our automation framework is written in Java and uses Testng. We use the @Test annotation to mark out our tests and provide the groups and a description for the test which we write in Gherkin. We use the test report created by Serenity

I have been trying to create a static constant class that we can use to build a test description so that it handle HTML tags rather than putting this into the String itself so its easier to read and so any HTML format that the test report uses can be done within this class rather than each

For example:

@Test( groups = { TestGroup.One, TestGroup.TWO }, description =
                "Given I am in Scenario One
" +
                "WhenI do something
" +
                "ThenI get a result")
        protected void testScript() {
    ...
    }

would actually look like:

@Test( groups = { TestGroup.One, TestGroup.TWO }, description =
            TestDescription
                .given("I am in Scenario One")
                .when("I do something")
                .then("I get a result");)
    protected void testScript() {
...
}

The code I currently have:

public final class TestDescription {

    private static String description = "";

    public static String given(final String given) {

        return "Given" + given + "
";
    }

    public static TestDescription when(final String when) {

        description = description + "When" + when + "
";
        return null;
    }

    public static TestDescription then(final String then) {

        description = description + "Then" + then + "
";
        return null;
    }

    public static TestDescription and(final String and) {

        description = description + "And" + and + "
";
        return null;
    }

    public static String build() {

        return description;
    }
}

Body:
Annotation attribute values must be compile-time constants in Java. See allowed expressions in Java documentation.

In TestNG the formatting of description attribute can be done through creating a custom TestNG @Test annotation transformer.

Sample code:

public class MyAnnotationTransformer implements IAnnotationTransformer {

    private static final String GIVEN = "given: ";
    private static final String WHEN = "when: ";
    private static final String THEN = "then: ";

    @Override
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
        if (testMethod != null) {
            String description = annotation.getDescription();
            if (description != null && !description.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String item : description.split("\\|")) {
                    if (item.startsWith(GIVEN)) {
                        sb.append("<b>Given</b> ").append(item.substring(GIVEN.length())).append("<br />");
                    } else if (item.startsWith(WHEN)) {
                        sb.append("<b>When</b> ").append(item.substring(WHEN.length())).append("<br />");
                    } else if (item.startsWith(THEN)) {
                        sb.append("<b>Then</b> ").append(item.substring(THEN.length())).append("<br />");
                    } else {
                        sb.append(item).append("<br />");
                    }
                }
                description = sb.toString();
                annotation.setDescription(description);
            }
        }
    }
}

Then the method would be annotated like this:

@Test( groups = { TestGroup.ONE, TestGroup.TWO }, description =
        "given: I am in Scenario One" +
        "|when: I do something" +
        "|then: I get a result")
protected void testScript() {
    //...
}

Note: when implementing custom TestNG listeners, we need to make sure theyare used by TestNG. (Listeners can be specified in the TestNG XML test suite or through other means.)

The resulting description in this case would be:

<b>Given</b> I am in Scenario One<br /><b>When</b> I do something<br /><b>Then</b> I get a result<br />

I hope this helps.


来源: stackexchange

问:
I want to convert this Cos up -1 to Tcl
can anyone tell me how can I convert this cos-1 to TCL, due to in TCL
just work with normal cos, not like this cos-1, also it calls "The inverse cosine".

答:
Tcl has always called the inverse cosine function acos; it's part of expressions:

```<code>% expr { acos(0.123) }
1.4474840516030245
</code>```

Result is in radians, of course.

ContentLicense: CC BY-SA 3.0

Title: I want to convert this Cos up -1 to Tcl

Body:
Tcl has always called the inverse cosine function acos; it's part of expressions:

% expr { acos(0.123) }
1.4474840516030245

Result is in radians, of course.


问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答:
Both Oracle and IBM offer offer versions of their flagship databases for free in a similar manner to SQL Server Express.  Both are excellent products if you wish to play with a 'real' database system.

Oracle 10g Express

IBM DB2 Express

Postgres is also well worth considering as it is also a 'real' relational database, having originally started as the much respected Ingres RDBMS in the 1980s.  However Postgress until recently was Unix-based and I've never found it particularly reliable installing on Windows.

Personally I would not recommend MySQL for your scenario - although the latest edition can finally be described as a RDBMS having evolved from what really was a collection of flat files with a limited SQL query interface it's peculiarities probably mitigate against it's use as a learning tool unless you are actually focused on MySQL.

There are a number of other less popular RDMSs you could consider.  Firebird has always been something of a favourite of mine as I used to code a lot of Delphi, and SQLite is a joy to work with in many circumstances.  It's also a pity you cannot use SQL Server Express as the SQL Server product range is simply the most solid product Microsoft produces and usually my database of choice on anything but the smallest, largest or most unsual installations

OwnerDisplayName: GordonG

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GordonG

OwnerDisplayName: Cruachan

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Mike Woodhouse


问:
C zip library that can create password protected zip files on windows?
Anyone know of a C library that can create password protected zip files on windows? It appears that the option to password protect zip files with the built-in zip utility has been removed from windows 7, but I don't think this is an issue.

Can either zziplib or the 7-Zip SDK do this?

答:
If you can use .NET, check out DotNetZip: http://dotnetzip.codeplex.com/

C++ .NET example to create password-protected ZIP:
http://cheeso.members.winisp.net/DotNetZipHelp/Code%20Examples/Cpp.htm


问:
Expire my link after X hour nodejs

I am sending this email to invite people for registration.That's my route

router.post('/invite-supervisor', (req,res) => {
    const email = req.body.invite_email;
    const secretToken = randomstring.generate();
  //  console.log('Email :',email);

    //Composing email
    const html = `Hi there

    To get registered please click on the following link and paste your secret token for registration.

    Token : ${secretToken}

    http://localhost:3000/signup/${secretToken}

    Have a good day!`;

    //p

    mailer.sendEmail('admin@teamfly.com',email,'Please signup through this link',html);
    req.flash('success','An invitation email sent to '+email);
    res.redirect('/');

});
```

Now I want to disable my link after few hours.How can I do it.

答:
The design I would follow to implement this would be the following :

In the table 'user' you will have a column : 'RegistrationToken', 'ExpirationTokenDate'

Create the user in base when you send him the invitation, set the RegistrationToken, his email, and the ExpirationTokenDate

If the user click on the link, check in base the mail+registrationToken :
then if the current date is greater than the expirationTokenDate, tell the link is expired, else, let the user register.

If you need to issue a new registrationToken for the user, just find his email in base and set a new RegistrationToken and update the ExpirationTokenDate.

Title: Expire my link after X hour nodejs

Body:
I am sending this email to invite people for registration.That's my route

router.post('/invite-supervisor', (req,res) => {
    const email = req.body.invite_email;
    const secretToken = randomstring.generate();
  //  console.log('Email :',email);

    //Composing email
    const html = `Hi there

    To get registered please click on the following link and paste your secret token for registration.

    Token : ${secretToken}

    http://localhost:3000/signup/${secretToken}

    Have a good day!`;

    //p

    mailer.sendEmail('admin@teamfly.com',email,'Please signup through this link',html);
    req.flash('success','An invitation email sent to '+email);
    res.redirect('/');

});

Now I want to disable my link after few hours.How can I do it.


问:
AngularJS incredibly slow performance when showing a table (1.6.5)
We are building an application to show a table with timetable data.
On the interface the user can set different filters.

I could use a data-grid which would speed up about everything.
I could use a table without grouping and use some sort of lazy fetching which would speed things up.
However we like the layout as is.
The consequence is that the watches are way over 2000 and we are experiencing bottlenecks. It is not that we show hundredths of rows.

How can we make this a bit more performant.
I tried track by, which didn't improve a thing. I tried bind-once but that didn't work either. (Honestly I have no clue how to make it work with key,value objects).
One performance trick might be changing the filters, move and chain them in the controller?

As you also can see, we re-use the same filters a lot, however this is necessary for the group by.

I also haven't seen any lazy-fetching mechanism which works with this kind of custom table / group by.

Hopefully you can help me to point me in the right direction, since I really kinda like the current layout.

The dataset is being displayed in a table and is grouped by date.

Example output:

hrefDateA | hrefDateB | hrefDateC | hrefDateD

DateA

RowA with columns

RowB with columns

RowC with columns

DateB

RowD with columns

RowE with columns

DateC

RowA with columns

RowB with columns

RowC with columns

....

```<code><div ng-if="includeDesktopTemplate" ng-show="whateverdata.length > 0">
        <div>
            Jump to:
            <a ng-href="#tableheader{{$index}}" ng-repeat="(key, value) in whateverdata | filter:filterA() | filter:filterB() | filter:filterC() | groupBy: 'someproperty'" class="someclass">
                {{key}}
            </a>
        </div>
        <hr />
        <table>
            <thead>
                <tr>
                    <th class="timetablerow">HeaderA</th>
                    <th class="timetablerow">HeaderB</th>
                    <th class="timetablerow">HeaderC</th>
                    <th class="timetablerow">HeaderD</th>
                    <th class="timetablerow">HeaderE</th>
                    <th class="timetablerow">HeaderF</th>
                </tr>
            </thead>
            <tbody ng-repeat="(key, value) in whateverdata | filter:filterA() | filter:filterB() | filter:filterC() | groupBy: 'someproperty'">
                <tr>
                    <td colspan="6" class="desktoptablegroupby" id="tableheader{{$index}}">
                        {{key}}
                    </td>
                </tr>
                <tr>
                    <td colspan="6">
                        <hr class="redbackground" />
                    </td>
                </tr>
                <tr ng-repeat="row in value | filter:filterA() | filter:filterB() | filter:filterC()" ng-class-odd="'odd'" ng-class-even="'even'">
                    <td class="timetablerow">
                        {{row.propertyA}}
                    </td>
                    <td class="timetablerow">
                        {{row.propertyB}}
                    </td>
                    <td class="timetablerow">
                        {{row.propertyC}} - {{row.propertyD}}
                    </td>
                    <td class="timetablerow">
                        {{row.propertyD}}
                    </td>
                    <td class="timetablerow">
                        {{row.propertyE}}
                    </td>
                    <td class="timetablerow">
                        <div ng-show="{{row.propertyF}}">
                                <md-tooltip md-direction="{{tooltip.tipDirection}}">
                                    {{row.propertyF}}
                                </md-tooltip>
                                <md-icon md-svg-src="~/Content/comment.svg">
                                </md-icon>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
        <br /><br />
    </div>
</code>```

If I include the code below, watches can go from 3k to 6k

```<code><div ng-show="{{row.propertyF}}">
                            <md-tooltip md-direction="{{tooltip.tipDirection}}">
                                {{row.propertyF}}
                            </md-tooltip>
                            <md-icon md-svg-src="~/Content/comment.svg">
                            </md-icon>
                    </div>
</code>```

Regarding the code above. One column would show an icon with a tooltip which contains the value of an extra field of the dataset, only when the field contains data. But this also gives issues when the filters are being used (so redraw of screen), since other rows are showing the tooltip then, even when the value of the field of the specific row does not contain a value.(DOM/update/filter issue?)

答:
This is a limitation by the way AngularJS handles change detection and rendering. There's really no easy solution - with emphasis on easy. What I've done on several occasions is use a technique often refered to as virtual-scroll/virtual-repeat. What it basically does is that it only renders the elements that can be seen in the viewport, but adds offsets to the top and bottom of the list/table to keep the scrollbar a constant size, regardless of how many elements are actually rendered. Then whenever you scroll, the elements that pop into view is seamlessly rendered before they become visible. This gives the illusion that it's a single long list/table, when it really only renders what is visible. </p>

<p>There are many libraries that implement this technique. I've personally got experience with the one called angular-vs-repeat but you should take a look at a few and evaluation which fits best your use case. I've also on one occasion implemented my own virtual scroll and it was certainly doable (my usecase in that scenario was that I needed virtual scroll to work both vertically and horizontally). </p>

Body:
We are building an application to show a table with timetable data.
On the interface the user can set different filters.

I could use a data-grid which would speed up about everything.
I could use a table without grouping and use some sort of lazy fetching which would speed things up.
However we like the layout as is.
The consequence is that the watches are way over 2000 and we are experiencing bottlenecks. It is not that we show hundredths of rows.

How can we make this a bit more performant.
I tried track by, which didn't improve a thing. I tried bind-once but that didn't work either. (Honestly I have no clue how to make it work with key,value objects).
One performance trick might be changing the filters, move and chain them in the controller?

As you also can see, we re-use the same filters a lot, however this is necessary for the group by.

I also haven't seen any lazy-fetching mechanism which works with this kind of custom table / group by.

Hopefully you can help me to point me in the right direction, since I really kinda like the current layout.

The dataset is being displayed in a table and is grouped by date.

Example output:

hrefDateA | hrefDateB | hrefDateC | hrefDateD

DateA

RowA with columns

RowB with columns

RowC with columns

DateB

RowD with columns

RowE with columns

DateC

RowA with columns

RowB with columns

RowC with columns

....

 0">

            Jump to:

                {{key}}

                    HeaderA
                    HeaderB
                    HeaderC
                    HeaderD
                    HeaderE
                    HeaderF

                        {{key}}

                        {{row.propertyA}}

                        {{row.propertyB}}

                        {{row.propertyC}} - {{row.propertyD}}

                        {{row.propertyD}}

                        {{row.propertyE}}

                                <md-tooltip md-direction="{{tooltip.tipDirection}}">
                                    {{row.propertyF}}
                                </md-tooltip>
                                <md-icon md-svg-src="~/Content/comment.svg">
                                </md-icon>

If I include the code below, watches can go from 3k to 6k

                            <md-tooltip md-direction="{{tooltip.tipDirection}}">
                                {{row.propertyF}}
                            </md-tooltip>
                            <md-icon md-svg-src="~/Content/comment.svg">
                            </md-icon>

Regarding the code above. One column would show an icon with a tooltip which contains the value of an extra field of the dataset, only when the field contains data. But this also gives issues when the filters are being used (so redraw of screen), since other rows are showing the tooltip then, even when the value of the field of the specific row does not contain a value.(DOM/update/filter issue?)

Body:
This is a limitation by the way AngularJS handles change detection and rendering. There's really no easy solution - with emphasis on easy. What I've done on several occasions is use a technique often refered to as virtual-scroll/virtual-repeat. What it basically does is that it only renders the elements that can be seen in the viewport, but adds offsets to the top and bottom of the list/table to keep the scrollbar a constant size, regardless of how many elements are actually rendered. Then whenever you scroll, the elements that pop into view is seamlessly rendered before they become visible. This gives the illusion that it's a single long list/table, when it really only renders what is visible.

There are many libraries that implement this technique. I've personally got experience with the one called angular-vs-repeat but you should take a look at a few and evaluation which fits best your use case. I've also on one occasion implemented my own virtual scroll and it was certainly doable (my usecase in that scenario was that I needed virtual scroll to work both vertically and horizontally).


问:
'AWSHTTPSConnection' object has no attribute 'ssl_context'
```<code>Not working
    root@49161b16e779:/# aws --version
    aws-cli/1.11.121 Python/3.5.2 Linux/4.10.0-32-generic botocore/1.5.84
    root@49161b16e779:/# aws s3 ls s3://my.bucket.path
    'AWSHTTPSConnection' object has no attribute 'ssl_context'

Working fine
    tada@tada-VirtualBox:~$ aws --version
    aws-cli/1.11.13 Python/3.5.2 Linux/4.10.0-32-generic botocore/1.4.70
</code>```

The above is a problem I'm getting lately, since somewhere between July 25 and Aug 3, 2017.

Docker is node:6.9.2. Also tried the 'ubuntu' image, same error.

I can't seem to find the error source. Anyone know how to solve it? Thanks.

答:
This is caused by a bug in AWS CLI, noted at https://github.com/boto/botocore/issues/1258#issuecomment-321787841, that mades it incompatible with newer versions of Requests. If you install awscli with Pip, you won't see the bug, because the version that you get from Pip has an old, compatible version of Requests baked into it. But if you've installed AWS CLI with Apt (or perhaps some other package managers), you'll have got a version of AWS CLI that uses the system's Requests module, exposing you to this bug.

To fix, either:

Remove whatever version of the AWS CLI you've got installed and reinstall it with Pip. This probably means running apt remove awscli && pip install awscli.

... OR, if you can't do that for some reason:

Downgrade Requests to version 2.12, which according to https://github.com/boto/botocore/issues/1258#issuecomment-331746809 is compatible with the old versions of AWS CLI, by running pip uninstall requests && pip install requests==2.12 or pip3 uninstall requests && pip3 install requests==2.12.

I believe this issue is fixed as of botocore v1.11.0, so eventually, once the version of awscli in Apt's repositories uses a botocore version >= v1.11.0, this bug should go away.

Body:
Not working
    root@49161b16e779:/# aws --version
    aws-cli/1.11.121 Python/3.5.2 Linux/4.10.0-32-generic botocore/1.5.84
    root@49161b16e779:/# aws s3 ls s3://my.bucket.path
    'AWSHTTPSConnection' object has no attribute 'ssl_context'

Working fine
    tada@tada-VirtualBox:~$ aws --version
    aws-cli/1.11.13 Python/3.5.2 Linux/4.10.0-32-generic botocore/1.4.70

The above is a problem I'm getting lately, since somewhere between July 25 and Aug 3, 2017.

Docker is node:6.9.2. Also tried the 'ubuntu' image, same error.

I can't seem to find the error source. Anyone know how to solve it? Thanks.


问:
Include overall average in R Grouped ggplot2
I am just learning R and finally have a task at work that I can use it for!  However, I am stumped on what I think should be a fairly easy/common thing.

I have this R code that generates the graph below

```<code>ggplot(data = subset(AverageHoldingTimes, CallPriority==1 & AverageCreatedToDispatct > 0 & CallCreatedHour %in% c(0,1,2,3,4,5,6,7)), mapping = aes(x=CallDate, y=AverageCreatedToDispatct)) +
  geom_smooth(se = FALSE, mapping = aes(color = AreaCommand)) +
  geom_smooth(se = FALSE, linetype = 2, color='red') +
  geom_vline(xintercept = as.POSIXct(as.Date(c("2016-09-15", "2017-08-15"))), linetype=4) +
  labs(y = "Average Number of Minutes to Dispatch", title = "Priority 1 Call Average Number of Minutes to Dispatch Midnight To 8 AM", x = "Call Date") +
  scale_colour_hue(name="Area Command", labels=c("FootHills", "NorthEast", "NorthWest", "SouthEast", "SouthWest", "Valley"), guide = guide_legend(override.aes = list(linetype = c(1, 1, 1, 1, 1, 1))))
</code>```

I would like for the dotted red line (the overall average for the Priority 1 calls) to be included in the legend. What do I need to change/add in order for that to be included?

Also, is there a way to add a label or text to the vertical lines?

答:
To get ggplot to include a geom layer in the legend it needs to have some aes() mapped to it. This doesn't have to be a column in data, we can assign any label as a character string. We'll use "average" here:

```<code>ggplot(mtcars, aes(wt, mpg)) +
  geom_smooth(se = FALSE, aes(color = as.factor(cyl), linetype = as.factor(cyl))) +
  geom_smooth(se = FALSE, aes(group = NULL, color = "average", linetype = "average")) +
  scale_color_manual(values = c("red","green","blue","black"), name = "Area Command") +
  scale_linetype_manual(values = c(1,1,1,3), name = "Area Command")
</code>```

The scale_x_manual()s are there to set values and to collapse the legends into a single box, so linetype and color share a single legend box, instead of separate ones.

Body:
I am just learning R and finally have a task at work that I can use it for!  However, I am stumped on what I think should be a fairly easy/common thing.

I have this R code that generates the graph below

ggplot(data = subset(AverageHoldingTimes, CallPriority==1 & AverageCreatedToDispatct > 0 & CallCreatedHour %in% c(0,1,2,3,4,5,6,7)), mapping = aes(x=CallDate, y=AverageCreatedToDispatct)) +
  geom_smooth(se = FALSE, mapping = aes(color = AreaCommand)) +
  geom_smooth(se = FALSE, linetype = 2, color='red') +
  geom_vline(xintercept = as.POSIXct(as.Date(c("2016-09-15", "2017-08-15"))), linetype=4) +
  labs(y = "Average Number of Minutes to Dispatch", title = "Priority 1 Call Average Number of Minutes to Dispatch Midnight To 8 AM", x = "Call Date") +
  scale_colour_hue(name="Area Command", labels=c("FootHills", "NorthEast", "NorthWest", "SouthEast", "SouthWest", "Valley"), guide = guide_legend(override.aes = list(linetype = c(1, 1, 1, 1, 1, 1))))

I would like for the dotted red line (the overall average for the Priority 1 calls) to be included in the legend. What do I need to change/add in order for that to be included?

Also, is there a way to add a label or text to the vertical lines?

Body:
To get ggplot to include a geom layer in the legend it needs to have some aes() mapped to it. This doesn't have to be a column in data, we can assign any label as a character string. We'll use "average" here:

ggplot(mtcars, aes(wt, mpg)) +
  geom_smooth(se = FALSE, aes(color = as.factor(cyl), linetype = as.factor(cyl))) +
  geom_smooth(se = FALSE, aes(group = NULL, color = "average", linetype = "average")) +
  scale_color_manual(values = c("red","green","blue","black"), name = "Area Command") +
  scale_linetype_manual(values = c(1,1,1,3), name = "Area Command")

The scale_x_manual()s are there to set values and to collapse the legends into a single box, so linetype and color share a single legend box, instead of separate ones.


问:
DLL File for windows 7 64bit
I'm porting my Windows XP application (wrote with C#) to Windows 7 application.
Now I'm using sqlite3.dll on my XP App (32bit) and I would download sqlite3.dll for 64bit machine.
For my purpose I've moved sqlite3.dll on my /bin folder and, obviously, when I try to start my app on windows 7 I receive an error.
So, where I download this file?

Please, help me...

Edit: I've downloaded sqlite3 http://www.sqlite.org/download.html

答:
The SQLite website only has the 32-bit .dll, to get a 64-bit one you'll have to download and compile the source yourself.

Since you're using C#, an easier way is to use System.Data.SQLite ( http://sqlite.phxsoftware.com/ ). They have a 64-bit download available, which is SQLite itself and their ADO.NET provider combined into one .dll. It's the easiest way to use SQLite on Windows with C# I think.

Update: New download URL is http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

Title: DLL File for windows 7 64bit


问:
Cumulative totals for every 3 rows
I have an employees table which has the following columns and sample data:

```<code>emp_id|name|salary|cumulative_sal
100     abc  1000   1000
101    gfh   2000   3000
102    jkl   3000   6000
103    ghi   5000   11000
104    tuv   7000   18000
105    mno   2000   20000
</code>```

Now, Iwant to update my cumulative salary in such a way that it is calculated for every 3 rows separately.
Sample

```<code>emp_id|name|salary|cumulative_sal
100     abc  1000   1000
101    gfh   2000   3000
102    jkl   3000   6000
103    ghi   5000   5000
104    tuv   7000   12000
105    mno   2000   14000
</code>```

Thnaks in advance

答:
Classify 3 rows into a group with row_number and then use a cumulative sum per the groups classified. Look at the results of inner query to see how groups are generated.

```<code>select emp_id,name,salary,sum(salary) over(partition by grp order by emp_id) as cumsum_sal
from (select emp_id,name,salary,(row_number() over(order by emp_id)-1)/3 as grp
      from tbl
     ) t
</code>```

Edit: Based on OP's comment to update the table. This can be done with a cte.

```<code>with cte as
(select emp_id,name,salary,cumulative_salary,
 sum(salary) over(partition by grp order by emp_id) as cumsum_sal
 from (select emp_id,name,salary,cumulative_salary,(row_number() over(order by emp_id)-1)/3 as grp
       from tbl
      ) t
)
update cte set cumulative_salary=cumsum_sal
</code>```

Title: Cumulative totals for every 3 rows

Body:
I have an employees table which has the following columns and sample data:

emp_id|name|salary|cumulative_sal
100     abc  1000   1000
101    gfh   2000   3000
102    jkl   3000   6000
103    ghi   5000   11000
104    tuv   7000   18000
105    mno   2000   20000

Now, Iwant to update my cumulative salary in such a way that it is calculated for every 3 rows separately.
Sample

emp_id|name|salary|cumulative_sal
100     abc  1000   1000
101    gfh   2000   3000
102    jkl   3000   6000
103    ghi   5000   5000
104    tuv   7000   12000
105    mno   2000   14000

Thnaks in advance

Body:
Classify 3 rows into a group with row_number and then use a cumulative sum per the groups classified. Look at the results of inner query to see how groups are generated.

select emp_id,name,salary,sum(salary) over(partition by grp order by emp_id) as cumsum_sal
from (select emp_id,name,salary,(row_number() over(order by emp_id)-1)/3 as grp
      from tbl
     ) t

Edit: Based on OP's comment to update the table. This can be done with a cte.

with cte as
(select emp_id,name,salary,cumulative_salary,
 sum(salary) over(partition by grp order by emp_id) as cumsum_sal
 from (select emp_id,name,salary,cumulative_salary,(row_number() over(order by emp_id)-1)/3 as grp
       from tbl
      ) t
)
update cte set cumulative_salary=cumsum_sal


问:
Listen to promise as a stream
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

```<code>const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)
</code>```

But it didn't work like a stream. So the output looks something like:

```<code>1
1 ' next '
done!
2
3
</code>```

How do I continue listening to the promise? Is this one of the problem Observable really solve?

答:
From the docs for Rx.Observable.fromPromise:

If the Promise resolves with a value, the output Observable emits that resolved value as a next, and then completes.

This describes exactly the behavior you're facing. You should use a generator function or Rx.Observable.create to solve this specific problem.

Title: Listen to promise as a stream

Body:
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)

But it didn't work like a stream. So the output looks something like:

1
1 ' next '
done!
2
3

How do I continue listening to the promise? Is this one of the problem Observable really solve?


问:
NOT ABLE TO CATCH ERRORS IN SQL SERVER 2008R2
I am trying to catch the errors in the below query using try catch block but even though query is throwing error, query is not hitting catch block. When I am executing the query without using TRY-CATCH block I am getting below error :

Msg 7314, Level 16, State 1, Procedure PROC_NAME, Line 97
  The OLE DB provider "SQLNCLI11" for linked server "LINKEDSERVER" does not contain the table ""DB_NAME"."dbo"."VIEW_NAME"". The table either does not exist or the current user does not have permissions on that table.
  Msg 2020, Level 16, State 1, Line 34
  The dependencies reported for entity "SP_NAME" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity.  Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist.

```<code>SELECT DISTINCT NAME INTO #ALL_SPS FROM SYSOBJECTS SO,SYSCOMMENTS SC WHERE SO.ID = SC.ID
AND TEXT LIKE '%LINKEDSERVER%'

CREATE TABLE #ERRORS
(
    ERRORNUMBER VARCHAR(100),
    ERRORSEVERITY   VARCHAR(100),
    ERRORSTATE  VARCHAR(100),
    ERRORPROCEDURE  VARCHAR(100),
    ERRORLINE   VARCHAR(100),
    ERRORMESSAGE VARCHAR(100)
)

CREATE TABLE #TEMP(SP_NAME VARCHAR(500),DB VARCHAR(100), LINKEDSERVER VARCHAR(100))

BEGIN
DECLARE @SP_NAME VARCHAR(MAX)
DECLARE @STARTTIME DATETIME =GETDATE()

DECLARE HDR_CURSOR CURSOR FOR

SELECT NAME FROM #ALL_SPS --IS TEMP TABLE IMPORTED FROM SHARED EXCEL

OPEN HDR_CURSOR

FETCH NEXT FROM HDR_CURSOR INTO @SP_NAME

WHILE (@@FETCH_STATUS = 0 )
   BEGIN
BEGIN TRY
BEGIN TRANSACTION;

    INSERT INTO #TEMP
    SELECT
    TBLSQLREFERENCEDENTITY.REFERENCED_ENTITY_NAME AS REFERENCEDENTITY,
    COALESCE(REFERENCED_DATABASE_NAME,DB_NAME()) AS REFERENCEDDATABASE,
    COALESCE(TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME,'CURRENT SERVER') AS REFERENCEDSERVER
    FROM SYS.DM_SQL_REFERENCED_ENTITIES('DBO.'+@SP_NAME, 'OBJECT') TBLSQLREFERENCEDENTITY
    WHERE  TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME ='LINKEDSERVER'
    GROUP BY REFERENCED_ENTITY_NAME,REFERENCED_DATABASE_NAME,REFERENCED_SERVER_NAME
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH

INSERT INTO #ERRORS
SELECT ERROR_NUMBER() AS ERRORNUMBER
     ,ERROR_SEVERITY() AS ERRORSEVERITY
     ,ERROR_STATE() AS ERRORSTATE
     ,ERROR_PROCEDURE() AS ERRORPROCEDURE
     ,ERROR_LINE() AS ERRORLINE
     ,ERROR_MESSAGE() AS ERRORMESSAGE;

END CATCH
  FETCH NEXT FROM HDR_CURSOR INTO @SP_NAME

 END
 CLOSE HDR_CURSOR
 DEALLOCATE HDR_CURSOR
 SELECT DATEDIFF(MS,@STARTTIME,GETDATE()) 'TIME TAKEN IN MS'
 SELECT DISTINCT * FROM #TEMP
 SELECT DISTINCT * FROM #ERRORS

END
</code>```

答:
You are mixing compile and run-time errors. Assuming you have permissions to that table, a better way to do this would be something like...

```<code>...
BEGIN TRANSACTION;

--see if that object exists in your linked server...
if(select 1
   from  YourLinkedServer.master.sys.objects
   where [name] = @SP_NAME) is not null

--if it exists, then insert from it...
INSERT INTO #TEMP
SELECT
TBLSQLREFERENCEDENTITY.REFERENCED_ENTITY_NAME AS REFERENCEDENTITY,
COALESCE(REFERENCED_DATABASE_NAME,DB_NAME()) AS REFERENCEDDATABASE,
COALESCE(TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME,'CURRENT SERVER') AS REFERENCEDSERVER
FROM SYS.DM_SQL_REFERENCED_ENTITIES('DBO.'+@SP_NAME, 'OBJECT') TBLSQLREFERENCEDENTITY
WHERE  TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME ='LINKEDSERVER'
GROUP BY REFERENCED_ENTITY_NAME,REFERENCED_DATABASE_NAME,REFERENCED_SERVER_NAME

COMMIT TRANSACTION;

...
</code>```

DETERMINE THE OBJECTS IN CURRENT DB THAT AREN"T IN THE LINKED SERVER

```<code>use [theDatabaseYourCareAbout]

select
    [name]
from sys.objects
where type in ('P','V') --procedures and views
except
select
    [name]
from YourLinkedServer.master.sys.objects
where type in ('P','V') --procedures and views
</code>```

Body:
I am trying to catch the errors in the below query using try catch block but even though query is throwing error, query is not hitting catch block. When I am executing the query without using TRY-CATCH block I am getting below error :

Msg 7314, Level 16, State 1, Procedure PROC_NAME, Line 97
  The OLE DB provider "SQLNCLI11" for linked server "LINKEDSERVER" does not contain the table ""DB_NAME"."dbo"."VIEW_NAME"". The table either does not exist or the current user does not have permissions on that table.
  Msg 2020, Level 16, State 1, Line 34
  The dependencies reported for entity "SP_NAME" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity.  Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist.

SELECT DISTINCT NAME INTO #ALL_SPS FROM SYSOBJECTS SO,SYSCOMMENTS SC WHERE SO.ID = SC.ID
AND TEXT LIKE '%LINKEDSERVER%'

CREATE TABLE #ERRORS
(
    ERRORNUMBER VARCHAR(100),
    ERRORSEVERITY   VARCHAR(100),
    ERRORSTATE  VARCHAR(100),
    ERRORPROCEDURE  VARCHAR(100),
    ERRORLINE   VARCHAR(100),
    ERRORMESSAGE VARCHAR(100)
)

CREATE TABLE #TEMP(SP_NAME VARCHAR(500),DB VARCHAR(100), LINKEDSERVER VARCHAR(100))

BEGIN
DECLARE @SP_NAME VARCHAR(MAX)
DECLARE @STARTTIME DATETIME =GETDATE()

DECLARE HDR_CURSOR CURSOR FOR

SELECT NAME FROM #ALL_SPS --IS TEMP TABLE IMPORTED FROM SHARED EXCEL

OPEN HDR_CURSOR

FETCH NEXT FROM HDR_CURSOR INTO @SP_NAME

WHILE (@@FETCH_STATUS = 0 )
   BEGIN
BEGIN TRY
BEGIN TRANSACTION;

    INSERT INTO #TEMP
    SELECT
    TBLSQLREFERENCEDENTITY.REFERENCED_ENTITY_NAME AS REFERENCEDENTITY,
    COALESCE(REFERENCED_DATABASE_NAME,DB_NAME()) AS REFERENCEDDATABASE,
    COALESCE(TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME,'CURRENT SERVER') AS REFERENCEDSERVER
    FROM SYS.DM_SQL_REFERENCED_ENTITIES('DBO.'+@SP_NAME, 'OBJECT') TBLSQLREFERENCEDENTITY
    WHERE  TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME ='LINKEDSERVER'
    GROUP BY REFERENCED_ENTITY_NAME,REFERENCED_DATABASE_NAME,REFERENCED_SERVER_NAME
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH

INSERT INTO #ERRORS
SELECT ERROR_NUMBER() AS ERRORNUMBER
     ,ERROR_SEVERITY() AS ERRORSEVERITY
     ,ERROR_STATE() AS ERRORSTATE
     ,ERROR_PROCEDURE() AS ERRORPROCEDURE
     ,ERROR_LINE() AS ERRORLINE
     ,ERROR_MESSAGE() AS ERRORMESSAGE;

END CATCH
  FETCH NEXT FROM HDR_CURSOR INTO @SP_NAME

 END
 CLOSE HDR_CURSOR
 DEALLOCATE HDR_CURSOR
 SELECT DATEDIFF(MS,@STARTTIME,GETDATE()) 'TIME TAKEN IN MS'
 SELECT DISTINCT * FROM #TEMP
 SELECT DISTINCT * FROM #ERRORS

END

Body:
You are mixing compile and run-time errors. Assuming you have permissions to that table, a better way to do this would be something like...

...
BEGIN TRANSACTION;

--see if that object exists in your linked server...
if(select 1
   from  YourLinkedServer.master.sys.objects
   where [name] = @SP_NAME) is not null

--if it exists, then insert from it...
INSERT INTO #TEMP
SELECT
TBLSQLREFERENCEDENTITY.REFERENCED_ENTITY_NAME AS REFERENCEDENTITY,
COALESCE(REFERENCED_DATABASE_NAME,DB_NAME()) AS REFERENCEDDATABASE,
COALESCE(TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME,'CURRENT SERVER') AS REFERENCEDSERVER
FROM SYS.DM_SQL_REFERENCED_ENTITIES('DBO.'+@SP_NAME, 'OBJECT') TBLSQLREFERENCEDENTITY
WHERE  TBLSQLREFERENCEDENTITY.REFERENCED_SERVER_NAME ='LINKEDSERVER'
GROUP BY REFERENCED_ENTITY_NAME,REFERENCED_DATABASE_NAME,REFERENCED_SERVER_NAME

COMMIT TRANSACTION;

...

DETERMINE THE OBJECTS IN CURRENT DB THAT AREN"T IN THE LINKED SERVER

use [theDatabaseYourCareAbout]

select
    [name]
from sys.objects
where type in ('P','V') --procedures and views
except
select
    [name]
from YourLinkedServer.master.sys.objects
where type in ('P','V') --procedures and views


问:
LESS lazy load issue - styles for ltr and rtl languages in same css file using mixins and variables
I have been provided with less files containing mixins and styles for LTR as well as RTL content on a webpage. The webpage shows only one type of content at a time, either LTR or RTL. Although I could have separate css for LTR and RTL styles and control which file is being loaded, I want them both to be in the same css file.

The mixins are controlled with an @lang variable as follows:

```<code>// file: mixins.less
.myMixin() when (@lang = ltr){
    float: left;
}

.myMixin() when (@lang = rtl){
    float: right;
}
</code>```

The mixins are being used in a styles.less file:

```<code>// file : styles.less
.myDiv{
    .myMixin();
}
</code>```

I want to output both the ltr and rtl styles in the same css by importing the styles.less file twice but with different value of the @lang variable for each import :

```<code>@import "mixin.less";

@lang: ltr;
@import (multiple) "styles.less";

@lang: rtl;
html{
    [dir=rtl] & {
        @import (multiple) "styles.less";
    }
}
</code>```

But this is obviously not working due to LESS's lazy loading of variables.

Expected output in the css file:

```<code>.myDiv {
  float:left;
}
[dir=rtl] html .myDiv {
  float:right;
}
</code>```

Actual output in the css file:

```<code>.myDiv {
  float:right;
}
[dir=rtl] html .myDiv {
  float:right;
}
</code>```

I do not have the liberty to modify the mixins.less file or the styles.less file. How would I go about achieving both ltr and rtl styles in the same css file?

Thanks in advance.

Link for @seven-phases-max : Example

答:
Posting the answer myself based on seven-phases-max's comments.

Previously the scope of the @lang variable was the same throughout and when lazy-loading kicked in, @lang was allocated the most recent value given to it. We need to isolate the scope when changing the value of @lang by adding an unnamed namespace and then importing the mixins and styles in the same scope which will produce the desired result.

Below is the code snippet:

```<code>@lang: ltr;
@import "mixin.less"; // value of @lang is ltr
@import "styles.less"; // creates ltr styles

& {
    @lang: rtl;
    html{
        [dir=rtl] & {
            @import (multiple) "mixin.less"; // value of @lang is rtl
            @import (multiple) "styles.less"; // creates rtl styles
        }
    }
}
</code>```

Output is as expected:

```<code>.myDiv {
  float: left;
}
[dir=rtl] html .myDiv {
  float: right;
}
</code>```

Body:
I have been provided with less files containing mixins and styles for LTR as well as RTL content on a webpage. The webpage shows only one type of content at a time, either LTR or RTL. Although I could have separate css for LTR and RTL styles and control which file is being loaded, I want them both to be in the same css file.

The mixins are controlled with an @lang variable as follows:

// file: mixins.less
.myMixin() when (@lang = ltr){
    float: left;
}

.myMixin() when (@lang = rtl){
    float: right;
}

The mixins are being used in a styles.less file:

// file : styles.less
.myDiv{
    .myMixin();
}

I want to output both the ltr and rtl styles in the same css by importing the styles.less file twice but with different value of the @lang variable for each import :

@import "mixin.less";

@lang: ltr;
@import (multiple) "styles.less";

@lang: rtl;
html{
    [dir=rtl] & {
        @import (multiple) "styles.less";
    }
}

But this is obviously not working due to LESS's lazy loading of variables.

Expected output in the css file:

.myDiv {
  float:left;
}
[dir=rtl] html .myDiv {
  float:right;
}

Actual output in the css file:

.myDiv {
  float:right;
}
[dir=rtl] html .myDiv {
  float:right;
}

I do not have the liberty to modify the mixins.less file or the styles.less file. How would I go about achieving both ltr and rtl styles in the same css file?

Thanks in advance.

Link for @seven-phases-max : <a href="http://less2css.org/#%7B%22less%22%3A%22%2F%2FMXINS%5Cn.myMixin()%20when%20(%40lang%20%3D%20ltr)%7B%5Cn%20%20%20%20float%3A%20left%3B%5Cn%7D%5Cn%5Cn.myMixin()%20when%20(%40lang%20%3D%20rtl)%7B%5Cn%20%20%20%20float%3A%20right%3B%5Cn%7D%5Cn%5Cn%40lang%3A%20ltr%3B%5Cn%2F%2F%20%40import%20%5C%22styles%5C%22%3B%5Cnhtml%20%7B%5Cn%20%20.myMixin()%3B%20%2F%2Ffloat%20should%20be%20left%5Cn%20%20result%3A%20%40lang%3B%5Cn%7D%5Cn%5Cn%26%20%7B%20%2F%2F%20%3C-%20unnamed%20namespace%5Cn%20%20%20%20%40lang%3A%20rtl%3B%5Cn%20%20%20%20html%20%7B%5Cn%20%20%20%20%20%20.myMixin()%3B%20%20%2F%2Ffloat%20should%20be%20right%5Cn%20%20%20%20%20%20result%3A%20%40lang%3B%5Cn%20%20%20%20%7D%5Cn%7D%22%7D" rel="nofollow noreferrer">Example

Body:
Posting the answer myself based on seven-phases-max's comments.

Previously the scope of the @lang variable was the same throughout and when lazy-loading kicked in, @lang was allocated the most recent value given to it. We need to isolate the scope when changing the value of @lang by adding an unnamed namespace and then importing the mixins and styles in the same scope which will produce the desired result.

Below is the code snippet:

@lang: ltr;
@import "mixin.less"; // value of @lang is ltr
@import "styles.less"; // creates ltr styles

& {
    @lang: rtl;
    html{
        [dir=rtl] & {
            @import (multiple) "mixin.less"; // value of @lang is rtl
            @import (multiple) "styles.less"; // creates rtl styles
        }
    }
}

Output is as expected:

.myDiv {
  float: left;
}
[dir=rtl] html .myDiv {
  float: right;
}


问:
Can't read line written on a file in C
I have been developing this project where every process after being forked writes his information on a file for the parent to read.
I have also written a small snippet for the parent to read this file, but every time I run this code it wont work.
Instead, when I manually write in the file in the following format:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

I can read allright, but when I run this code:

```<code>  #include "header.h"

  struct Individui {
       pid_t pid;
       char tipo[50];
       char nome[50];
       unsigned long genoma;
  };

int main(int argc, char *argv[]) {

    Individuo individuo;
    srand(getpid());

    int min = 2;
    int max = atoi(argv[2]);
    int diff = max - min;
    int r;
    r = rand() % (diff + 1) + min;

    char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand() % 26];

    individuo.pid = getpid();
    strcpy( individuo.tipo, argv[0]);
    strcpy( individuo.nome, &randomletter);
    individuo.genoma = r;

    FILE *f = fopen("dati.txt", "a");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    fprintf(f, "%d | %s | %s | %lu\r", individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);

    fclose(f);

    return 0;
}
</code>```

And then read the file with this code, it doesn't work:

```<code>int main(){
    char name[4], type[4];
    int pids[4];
    unsigned long genome[4];
    int i = 0;

    FILE * file = fopen("dati.txt", "r"); // "r" = read
    while(fscanf(file, "%d | %c | %c | %ld\n", &pids[i], &name[i], &type[i], &genome[i]) != EOF){
        i++;
    }

    printf ("%d %c %c %lu\n", pids[0], name[0], type[0], genome[0]);
    printf ("%d %c %c %lu\n", pids[1], name[1], type[1], genome[1]);
    printf ("%d %c %c %lu\n", pids[2], name[2], type[2], genome[2]);
}
</code>```

From what I was able to understand, the length of the lines I write with the process code is very long, and the code to read the file doesn't support it. I'm new to C so I can't really know where I'm mistaken, and I hope somebody might help.

答:
Your first program isn't writing the data in the format the second program expects.

The first problem is here:

```<code>strcpy( individuo.nome, &randomletter);
</code>```

The strcpy function expects a pointer to a null terminated string for it's second argument.  You're instead passing a pointer to a single character.  As a result, the function will attempt to read memory past the location of that single variable.  Reading outside of memory bounds invokes undefined behavior.

The other issue is here:

```<code>fprintf(f, "%d | %s | %s | %lu\r",
        individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);
</code>```

Your second program expects a single character for the second and third elements, but you're instead writing strings for both of these.  Also, \r is not a newline but a linefeed.  A newline is \n.

The fix:

First change your structure to use individual characters instead of strings, since you'll only be writing characters:

```<code>  struct Individui {
       pid_t pid;
       char tipo;
       char nome;
       unsigned long genoma;
  };
</code>```

Then change how you assign to those fields:

```<code>individuo.tipo = argv[1][0]; // assumes first command line argument is char to print
individuo.nome = randomletter;
</code>```

Then write single characters and fix the newline:

```<code>fprintf(f, "%d | %c | %c | %lu\n",
        individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);
</code>```

Title: Can't read line written on a file in C

Body:
I have been developing this project where every process after being forked writes his information on a file for the parent to read.
I have also written a small snippet for the parent to read this file, but every time I run this code it wont work.
Instead, when I manually write in the file in the following format:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

I can read allright, but when I run this code:

  #include "header.h"

  struct Individui {
       pid_t pid;
       char tipo[50];
       char nome[50];
       unsigned long genoma;
  };

int main(int argc, char *argv[]) {

    Individuo individuo;
    srand(getpid());

    int min = 2;
    int max = atoi(argv[2]);
    int diff = max - min;
    int r;
    r = rand() % (diff + 1) + min;

    char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand() % 26];

    individuo.pid = getpid();
    strcpy( individuo.tipo, argv[0]);
    strcpy( individuo.nome, &randomletter);
    individuo.genoma = r;

    FILE *f = fopen("dati.txt", "a");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    fprintf(f, "%d | %s | %s | %lu\r", individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);

    fclose(f);

    return 0;
}

And then read the file with this code, it doesn't work:

int main(){
    char name[4], type[4];
    int pids[4];
    unsigned long genome[4];
    int i = 0;

    FILE * file = fopen("dati.txt", "r"); // "r" = read
    while(fscanf(file, "%d | %c | %c | %ld\n", &pids[i], &name[i], &type[i], &genome[i]) != EOF){
        i++;
    }

    printf ("%d %c %c %lu\n", pids[0], name[0], type[0], genome[0]);
    printf ("%d %c %c %lu\n", pids[1], name[1], type[1], genome[1]);
    printf ("%d %c %c %lu\n", pids[2], name[2], type[2], genome[2]);
}

From what I was able to understand, the length of the lines I write with the process code is very long, and the code to read the file doesn't support it. I'm new to C so I can't really know where I'm mistaken, and I hope somebody might help.

Body:
Your first program isn't writing the data in the format the second program expects.

The first problem is here:

strcpy( individuo.nome, &randomletter);

The strcpy function expects a pointer to a null terminated string for it's second argument.  You're instead passing a pointer to a single character.  As a result, the function will attempt to read memory past the location of that single variable.  Reading outside of memory bounds invokes undefined behavior.

The other issue is here:

fprintf(f, "%d | %s | %s | %lu\r",
        individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);

Your second program expects a single character for the second and third elements, but you're instead writing strings for both of these.  Also, \r is not a newline but a linefeed.  A newline is \n.

The fix:

First change your structure to use individual characters instead of strings, since you'll only be writing characters:

  struct Individui {
       pid_t pid;
       char tipo;
       char nome;
       unsigned long genoma;
  };

Then change how you assign to those fields:

individuo.tipo = argv[1][0]; // assumes first command line argument is char to print
individuo.nome = randomletter;

Then write single characters and fix the newline:

fprintf(f, "%d | %c | %c | %lu\n",
        individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);


问:
Stream .mjpeg video view-able on both Chrome and IE11
I hosted a .mjpeg file locally http://127.0.0.1/web/Images/Stream/somevideo.mjpeg

I tried a few codes in my cshtml page.

1. Video tag method

```<code>    <video src="http://127.0.0.1/web/Images/Stream/somevideo.mjpeg" controls></video>
</code>```

2. img tag method

```<code><img src="http://127.0.0.1/web/Images/Stream/somevideo.mjpeg"/>
</code>```

3. motionjpeg javascript method

The code below copied from here

```<code><img id="motionjpeg" src="http://127.0.0.1/web/Images/Stream/somevideo.mjpeg" />
<script>
        //Using jQuery for simplicity
        function motionjpeg(id) {
            var image = $(id), src;

            if (!image.length) return;

            src = image.attr("src");
            if (src.indexOf("?") < 0) {
                image.attr("src", src + "?"); // must have querystring
            }

            image.on("load", function() {
                // this cause the load event to be called "recursively"
                this.src = this.src.replace(/?[^\n]*$/, "?") +
                    (new Date()).getTime(); // 'this' refers to the image
            });
        }

        $(document).ready(function() {
            motionjpeg("#motionjpeg"); // Use the function on the image
        });
</script>
</code>```

4. clipchamp javascript method

The only code that works, however only on Chrome but not IE

```<code><div id="mjpeg_player" style="width:600px;"></div>
<script src='http://127.0.0.1/web/Scripts/jquery-clipchamp-mjpeg-player-plugin-master/src/jquery.clipchamp.mjpeg.player.js'></script>
<script>
        $(document).ready(function() {

            var mjpegUrl = "http://127.0.0.1/web/Images/Stream/somevideo.mjpeg";
            var fps = 20;
            var autoloop = true;

            $('#mjpeg_player').clipchamp_mjpeg_player(mjpegUrl, fps, autoloop,
                function(wrapperElement, playerInterface) {
                    /*
                    $('#mjpeg_player_stop').click(function(){
                        playerInterface.finish();
                    });
                    */
                });
        });
</script>
</code>```

FYI, I configured the MIME type of .mpjeg as application/octet-stream

答:
Have you tried multipart/x-mixed-replace ?
You will also have to provide boundary parameter so it will look something like this: multipart/x-mixed-replace; boundary=--boundary you will have to figure out which boundary is used on your hosted mjpeg file to delimit separate frame contents.

Body:
I hosted a .mjpeg file locally http://127.0.0.1/web/Images/Stream/somevideo.mjpeg

I tried a few codes in my cshtml page.

1. Video tag method

    <video src="http://127.0.0.1/web/Images/Stream/somevideo.mjpeg" controls></video>

2. img tag method

3. motionjpeg javascript method

The code below copied from here

4. clipchamp javascript method

The only code that works, however only on Chrome but not IE

FYI, I configured the MIME type of .mpjeg as application/octet-stream


问:
Set a number of spinners to default
I have 18 spinners in a GridLayout with values assigned to each one manually(no adapters) in the activity layout. Now I want a "clear button" to call a method:"onClickClear" that sets each spinner to the default value.

Is there a way to do that without writing a reference to 18 spinners and using setSelection(0). I'm pretty new to Android and this is a proof of concept project I'm doing :)

答:
Laziest and not the best solution.

Find a reference to their parent and loop over it's children

```<code>for (int i = 0; i < viewGroup.getChildCount(); i++) {
    View currentView = viewGroup.getChildAt(i);
    if (currentView instanceof Spinner) {
        ((Spinner) currentView).setSelection(0);
    }
}
</code>```

Or you can hold them in an array and loop over them, but you have to find them 18 times to populate the array.

Title: Set a number of spinners to default

Body:
Laziest and not the best solution.

Find a reference to their parent and loop over it's children

for (int i = 0; i < viewGroup.getChildCount(); i++) {
    View currentView = viewGroup.getChildAt(i);
    if (currentView instanceof Spinner) {
        ((Spinner) currentView).setSelection(0);
    }
}

Or you can hold them in an array and loop over them, but you have to find them 18 times to populate the array.


答:
Bugfixes writer:

```<code>char randomletter[2];
randomletter[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand() % 26];
randomletter[1] = '\0';

strcpy( individuo.nome, randomletter);

fprintf(f, "%d | %s | %s | %lu\n",
    individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);
</code>```

Bugfixes reader:

```<code>void read() {
    char name[4][50], type[4][50];
    int pids[4];
    unsigned long genome[4];

    FILE * file = fopen("dati.txt", "r"); // "r" = read
    for (int i = 0; i < 4; i++) {
        if (fscanf(file, "%d | %s | %s | %lu", &pids[i], name[i], type[i], &genome[i]) != 4)
            break;

        printf ("%d %s %s %lu\n", pids[i], name[i], type[i], genome[i]);
    }
}
</code>```

Title: Can't read line written on a file in C

Body:
Bugfixes writer:

char randomletter[2];
randomletter[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand() % 26];
randomletter[1] = '\0';

strcpy( individuo.nome, randomletter);

fprintf(f, "%d | %s | %s | %lu\n",
    individuo.pid, individuo.nome, individuo.tipo, individuo.genoma);

Bugfixes reader:

void read() {
    char name[4][50], type[4][50];
    int pids[4];
    unsigned long genome[4];

    FILE * file = fopen("dati.txt", "r"); // "r" = read
    for (int i = 0; i < 4; i++) {
        if (fscanf(file, "%d | %s | %s | %lu", &pids[i], name[i], type[i], &genome[i]) != 4)
            break;

        printf ("%d %s %s %lu\n", pids[i], name[i], type[i], genome[i]);
    }
}


问:
Setting up widget button for performing background job
I'm trying to create an app widget that, when pressed, triggers a background job that saves time+location to a database.

From what I have been able to gather so far, the setup I probably want consists of an AppWidgetProvider subclass whose onUpdate() is responsible for setting up a PendingIntent on a RemoteView representing the widget button. Its onReceive() method would catch the broadcast from the PendingIntent, and I would perhaps start off a service from here to perform the background job.

If I'm on the right track so far, I have one challenge, which is that onUpdate() is not triggered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing). Do I have to set the widget up with a configurationactivity, which in turn triggers AppWidgetProvider.onUpdate(), or is there a simpler solution to this?

If I'm not on the right track at all, any pointers to a better way of achieving what I'm trying to achieve would be very much appreciated. :)

Update:

Thought I might post some of the code here as well. Here is the receiver definition from the manifest:

```<code><receiver android:name=".widget.QuickAddWidgetProvider" >
  <intent-filter>
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  </intent-filter>
  <meta-data android:name="android.appwidget.provider"
             android:resource="@xml/quickadd_widget_info" />
</receiver>
</code>```

This is my resource file, defining the widget:

```<code><?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="72dp"
    android:minHeight="72dp"
    android:initialLayout="@layout/quickadd_widget"
    android:updatePeriodMillis="0">
</appwidget-provider>
</code>```

This is QuickAddWidgetProvider:

```<code>public class QuickAddWidgetProvider extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("QuickAdd", "onReceive()");
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.v("QuickAdd", "onUpdate()");
    }
}
</code>```

答:
If I'm on the right track so far

Yes!

I have one challenge, which is that onUpdate() is not triggered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing)

Well, it should. Make sure your AppWidgetProvider's entry in the manifest has the right <intent-filter> to receive updates:

```<code><receiver android:name=".AppWidget" android:label="@string/app_name" android:icon="@drawable/icon">
        <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider"/>
</receiver>
</code>```

Body:
I'm trying to create an app widget that, when pressed, triggers a background job that saves time+location to a database.

From what I have been able to gather so far, the setup I probably want consists of an AppWidgetProvider subclass whose onUpdate() is responsible for setting up a PendingIntent on a RemoteView representing the widget button. Its onReceive() method would catch the broadcast from the PendingIntent, and I would perhaps start off a service from here to perform the background job.

If I'm on the right track so far, I have one challenge, which is that onUpdate() is not triggered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing). Do I have to set the widget up with a configurationactivity, which in turn triggers AppWidgetProvider.onUpdate(), or is there a simpler solution to this?

If I'm not on the right track at all, any pointers to a better way of achieving what I'm trying to achieve would be very much appreciated. :)

Update:

Thought I might post some of the code here as well. Here is the receiver definition from the manifest:

<receiver android:name=".widget.QuickAddWidgetProvider" >
  <intent-filter>
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  </intent-filter>
  <meta-data android:name="android.appwidget.provider"
             android:resource="@xml/quickadd_widget_info" />
</receiver>

This is my resource file, defining the widget:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="72dp"
    android:minHeight="72dp"
    android:initialLayout="@layout/quickadd_widget"
    android:updatePeriodMillis="0">
</appwidget-provider>

This is QuickAddWidgetProvider:

public class QuickAddWidgetProvider extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("QuickAdd", "onReceive()");
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.v("QuickAdd", "onUpdate()");
    }
}

Body:
If I'm on the right track so far

Yes!

I have one challenge, which is that onUpdate() is not triggered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing)

Well, it should. Make sure your AppWidgetProvider's entry in the manifest has the right <intent-filter> to receive updates:

<receiver android:name=".AppWidget" android:label="@string/app_name" android:icon="@drawable/icon">
        <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider"/>
</receiver>


问:
Sum integer list when next integer is the same value
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

```<code>input1 = [int(i) for i in str(1234441122)]
x= 0
</code>```

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

答:
You are simply iterating on string and converting character to integer. You need to iterate and compare to next character.

```<code>a = str(1234441122)
sum = 0
for i,j in enumerate(a[:-1]):
    if a[i] == a[i+1]:
        sum+=int(a[i])
print(sum)
</code>```

Output

```<code>11
</code>```

Body:
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

input1 = [int(i) for i in str(1234441122)]
x= 0

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

Body:
You are simply iterating on string and converting character to integer. You need to iterate and compare to next character.

a = str(1234441122)
sum = 0
for i,j in enumerate(a[:-1]):
    if a[i] == a[i+1]:
        sum+=int(a[i])
print(sum)

Output

11


问:
jQuery to update checkbox value, depending on radio field?
Goal is to update checkbox fields to equal TRUE or FALSE, depending which radio button option is picked. If I select FALSE, then the checkboxes must be unchecked.

I'm only able to get the checkboxes ticked if I select TRUE. Is it because I defined that as a value?

```<code>     $(function() {
var MAIN= $("input[type='radio'][value='TRUE']");
var marketing1 = $("input[type='checkbox'][value='']");
var marketing2 = $("input[type='checkbox'][value='']");

    MAIN.on('change', function()
        {
      if ($(this).val() == "TRUE")  {
             marketing1.prop('checked',this.checked);
             marketing2.prop('checked',this.checked);
        } if ($(this).val() == "FALSE") {
             marketing1.prop('checked',this.checked, false);
             marketing2.prop('checked',this.checked, false);
        }

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

From HTML

```<code>     <input type="radio" name="MAIN" value="TRUE"/> Yes
     <input type="radio" name="MAIN" value="FALSE"/> No

First -  <input type="checkbox" name="marketing1" value=""/>
Second -  <input type="checkbox" name="marketing2" value=""/>
</code>```

答:
There is no need for this and checked. I've adjusted your code:

$(function() {
  var MAIN= $("input[type='radio']");
  var marketing1 = $("input[type='checkbox'][name='marketing1']");
  var marketing2 = $("input[type='checkbox'][name='marketing2']");

    MAIN.on('change', function()
        {
        if ($(this).val() == "TRUE")  {
          marketing1.prop('checked',true);
          marketing2.prop('checked',true);
        } else {
          marketing1.prop('checked',false);
          marketing2.prop('checked',false);
        }

    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="MAIN" value="TRUE"/> Yes
<input type="radio" name="MAIN" value="FALSE"/> No
<br>
First -  <input type="checkbox" name="marketing1" value=""/>
Second -  <input type="checkbox" name="marketing2" value=""/> </code>```

Body:
Goal is to update checkbox fields to equal TRUE or FALSE, depending which radio button option is picked. If I select FALSE, then the checkboxes must be unchecked.

I'm only able to get the checkboxes ticked if I select TRUE. Is it because I defined that as a value?

     $(function() {
var MAIN= $("input[type='radio'][value='TRUE']");
var marketing1 = $("input[type='checkbox'][value='']");
var marketing2 = $("input[type='checkbox'][value='']");

    MAIN.on('change', function()
        {
      if ($(this).val() == "TRUE")  {
             marketing1.prop('checked',this.checked);
             marketing2.prop('checked',this.checked);
        } if ($(this).val() == "FALSE") {
             marketing1.prop('checked',this.checked, false);
             marketing2.prop('checked',this.checked, false);
        }

    });
});

From HTML

     <input type="radio" name="MAIN" value="TRUE"/> Yes
     <input type="radio" name="MAIN" value="FALSE"/> No

First -  <input type="checkbox" name="marketing1" value=""/>
Second -  <input type="checkbox" name="marketing2" value=""/>

Body:
There is no need for this and checked. I've adjusted your code:

$(function() {
  var MAIN= $("input[type='radio']");
  var marketing1 = $("input[type='checkbox'][name='marketing1']");
  var marketing2 = $("input[type='checkbox'][name='marketing2']");

    MAIN.on('change', function()
        {
        if ($(this).val() == "TRUE")  {
          marketing1.prop('checked',true);
          marketing2.prop('checked',true);
        } else {
          marketing1.prop('checked',false);
          marketing2.prop('checked',false);
        }

    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="MAIN" value="TRUE"/> Yes
<input type="radio" name="MAIN" value="FALSE"/> No
<br>
First -  <input type="checkbox" name="marketing1" value=""/>
Second -  <input type="checkbox" name="marketing2" value=""/>


问:
consecutive matches in regex (R)
I'm trying to write a regex expression (under R) that matches all the words containing 3 letters in this text:

```<code>tex= "As you are now so once were we"
</code>```

My first attempt is to select words containing 3 letters surrounded by spaces:

```<code>matches=str_match_all(tex," [a-z]{3} ")
</code>```

It's supposed to match " you ", " are " and " now ". But, since some of these spaces are shared between the matched strings, I only get " you " and " now ".

Is there a way to fix this issue ?

Thanks in advance

答:
```<code> tex= "As you are now so once were we"
</code>```

Base R function

```<code>regmatches(tex , gregexpr('\\b[a-z]{3}\\b' , tex))[[1]]

 [1] "you" "are" "now"
</code>```

Title: consecutive matches in regex (R)

Body:
I'm trying to write a regex expression (under R) that matches all the words containing 3 letters in this text:

tex= "As you are now so once were we"

My first attempt is to select words containing 3 letters surrounded by spaces:

matches=str_match_all(tex," [a-z]{3} ")

It's supposed to match " you ", " are " and " now ". But, since some of these spaces are shared between the matched strings, I only get " you " and " now ".

Is there a way to fix this issue ?

Thanks in advance

Body:
 tex= "As you are now so once were we"

Base R function

regmatches(tex , gregexpr('\\b[a-z]{3}\\b' , tex))[[1]]

 [1] "you" "are" "now"


问:
NSTask Does Not Terminate
I'm trying to use NSTask to run the UNIX 'apropos' command. Here's my code:

```<code>NSTask *apropos = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
[apropos setLaunchPath:@"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];
</code>```

The problem is that this never returns. I also tried using Apple's example code (TaskWrapper) and it returns the output (in three segments) but it never calls the processFinished handler.

Furthermore, the appendOutput: handler receives duplicates. So, for example, if apropos returns this:

1
2
3
4
5

I might receive something like this:

1
2
3

1
2
3
4

5

(grouped into 3 append messages).

I note that Apropos displays the output in a format where it's possible to scroll up and down in the command line instead of just directly outputting the data straight to standard output; how do I read this reliably through NSTask and NSPipe?

答:
I’ve just tested this program and it works fine: the program terminates and /tmp/apropos.txt contains the output of apropos.

```<code>#import <Foundation/Foundation.h>

int main()
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSTask *apropos = [[[NSTask alloc] init] autorelease];
    NSPipe *pipe = [[[NSPipe alloc] init] autorelease];
    NSFileHandle *readHandle = [pipe fileHandleForReading];
    [apropos setLaunchPath:@"/usr/bin/apropos"];
    [apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
    [apropos setStandardOutput:pipe];
    [apropos launch];
    [apropos waitUntilExit];

    NSString *output = [[[NSString alloc]
        initWithData:[readHandle readDataToEndOfFile]
            encoding:NSUTF8StringEncoding] autorelease];

    [output writeToFile:@"/tmp/apropos.txt" atomically:YES
        encoding:NSUTF8StringEncoding error:NULL];

    [pool drain];
    return 0;
}
</code>```

Are you by any chance using NSLog() to inspect the output? If so, you might need to set a pipe for stdin as explained in this answer of mine to an NSTask related question. It seems that NSLog() sending data to stderr affects NSTask.

Title: NSTask Does Not Terminate

Body:
I'm trying to use NSTask to run the UNIX 'apropos' command. Here's my code:

NSTask *apropos = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
[apropos setLaunchPath:@"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];

The problem is that this never returns. I also tried using Apple's example code (TaskWrapper) and it returns the output (in three segments) but it never calls the processFinished handler.

Furthermore, the appendOutput: handler receives duplicates. So, for example, if apropos returns this:

1
2
3
4
5

I might receive something like this:

1
2
3

1
2
3
4

5

(grouped into 3 append messages).

I note that Apropos displays the output in a format where it's possible to scroll up and down in the command line instead of just directly outputting the data straight to standard output; how do I read this reliably through NSTask and NSPipe?

Body:
I’ve just tested this program and it works fine: the program terminates and /tmp/apropos.txt contains the output of apropos.

#import <Foundation/Foundation.h>

int main()
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSTask *apropos = [[[NSTask alloc] init] autorelease];
    NSPipe *pipe = [[[NSPipe alloc] init] autorelease];
    NSFileHandle *readHandle = [pipe fileHandleForReading];
    [apropos setLaunchPath:@"/usr/bin/apropos"];
    [apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
    [apropos setStandardOutput:pipe];
    [apropos launch];
    [apropos waitUntilExit];

    NSString *output = [[[NSString alloc]
        initWithData:[readHandle readDataToEndOfFile]
            encoding:NSUTF8StringEncoding] autorelease];

    [output writeToFile:@"/tmp/apropos.txt" atomically:YES
        encoding:NSUTF8StringEncoding error:NULL];

    [pool drain];
    return 0;
}

Are you by any chance using NSLog() to inspect the output? If so, you might need to set a pipe for stdin as explained in this answer of mine to an NSTask related question. It seems that NSLog() sending data to stderr affects NSTask.


问:
Python/Pandas Regex for a Wide Variety of Dates
I have a task to extract a wide variety of dates from a text file using Python.

As per the requirements, the following date formats must be properly extracted from the text file:

04/20/2009; 04/20/09; 4/20/09; 4/3/09

Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;

20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009

Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009

Feb 2009; Sep 2009; Oct 2010 (shall be parsed to 02/01/2009, 09/01/2009 etc)

6/2008; 12/2009 (shall be parsed to 06/01/2008 etc).

2009; 2010 (shall be parsed to 01/01/2009 and 01/01/2010)

Regex to the rescue!

Came up with the following expression:

```<code>(((0?[1-9]|1[0-2])((\/)|(-)))?(((0?[1-9]|[1-2][0-9]|3[0-1])((\/)|(-))))((19[0-9][0-9])|(20[0-1]{1}[0-9])|([0-9][0-9]))|((19[0-9][0-9])|(20[0-1]{1}[0-9])))|((0[1-9])|(1[0-9])|(2[0-9])|(3[0-1]))?(\D)?(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)((\s|\.|-)((19[0-9][0-9])|(20[0-9][0-9])))
</code>```

I was able to debug it with Regex101 for all use cases.

However, when I try to run it over a Pandas dataframe using the code below, no matches are found for some of the cases - ("df" stands for a Pandas dataframe where each of the rows contains raw text with a date in one of the formats above)

```<code>import re

pattern = '(((0?[1-9]|1[0-2])((\/)|(-)))?(((0?[1-9]|[1-2][0-9]|3[0-1])((\/)|(-))))((19[0-9][0-9])|(20[0-1]{1}[0-9])|([0-9][0-9]))|((19[0-9][0-9])|(20[0-1]{1}[0-9])))|((0[1-9])|(1[0-9])|(2[0-9])|(3[0-1]))?(\D)?(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)((\s|\.|-)((19[0-9][0-9])|(20[0-9][0-9])))'

flags = re.IGNORECASE

m = df.str.extract(pattern, flags)
</code>```

Cases where there's not a match include:

AFeb 1977: Symmes Hospital\n

"NV fire fighter died Sep 2007 while working.  Was friend from deployment to San Marino and trainings for years prior.  Still troubling to pt.  Didn't go to his funeral.  Spiritual/Religion:\n

's Cathy Bowers is a 50 yo single Caucasian female who presents to the ANH Eating Disorders Department for an evaluation and treatment recommendations for low weight.  She shared that she has recently lost a great deal of weight and is having difficulty meeting her calorie needs due to difficulties with gagging/swallowing, and aversions to specific food textures.  Specifically, since May 2012, she has lost 18 lbs, going from 128 lbs (BMI = 19.5, normal range) to 110.2 lbs (BMI = 16.8, underweight range) at a height of 5\'8" tall.  She has had amenorrhea for 2 months.  Her current weight is her lowest since high school, when she was a model and weighed 98 lbs (BMI = 14.9, underweight range).  At that time, she had amenorrhea, felt pressure to be thin in order to keep her job, and most likely met criteria for frank anorexia nervosa nervosa-restricting type.\n'

For all of these cases, I was able to properly debug the expression and validate them on Reg101.

This makes me think that maybe there's a mismatch between the Python parser/version used by Reg101 and the Python version I'm using (3) - or maybe a parameter that I'm not aware of.

Anyone has a clue?

Thanks in advance!

答:
Code

See regex in use here

```<code>\d+/\d+(?:/\d+)?|(?:\d+ )?(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[.,]?(?:-\d+-\d+| \d+(?:th|rd|st|nd)?,? \d+| \d+)|\d{4}
</code>```

Results

Input

04/20/2009; 04/20/09; 4/20/09; 4/3/09 Mar-20-2009; Mar 20, 2009; March
  20, 2009; Mar. 20, 2009; Mar 20 2009; 20 Mar 2009; 20 March 2009; 20
  Mar. 2009; 20 March, 2009 Mar 20th, 2009; Mar 21st, 2009; Mar 22nd,
  2009 Feb 2009; Sep 2009; Oct 2010 (shall be parsed to 02/01/2009,
  09/01/2009 etc) 6/2008; 12/2009 (shall be parsed to 06/01/2008 etc).
  2009; 2010 (shall be parsed to 01/01/2009 and 01/01/2010) AFeb 1977:
  Symmes Hospital\n NV fire fighter died Sep 2007 while working. Was
  friend from deployment to San Marino and trainings for years prior.
  Still troubling to pt. Didn't go to his funeral. Spiritual/Religion:
  's Cathy Bowers is a 50 yo single Caucasian female who presents to the
  ANH Eating Disorders Department for an evaluation and treatment
  recommendations for low weight. She shared that she has recently lost
  a great deal of weight and is having difficulty meeting her calorie
  needs due to difficulties with gagging/swallowing, and aversions to
  specific food textures. Specifically, since May 2012, she has lost 18
  lbs, going from 128 lbs (BMI = 19.5, normal range) to 110.2 lbs (BMI =
  16.8, underweight range) at a height of 5\'8" tall. She has had amenorrhea for 2 months. Her current weight is her lowest since high
  school, when she was a model and weighed 98 lbs (BMI = 14.9,
  underweight range). At that time, she had amenorrhea, felt pressure to
  be thin in order to keep her job, and most likely met criteria for
  frank anorexia nervosa nervosa-restricting type.

Output

Below shows matches only.

```<code>04/20/2009
04/20/09
4/20/09
4/3/09
Mar-20-2009
Mar 20, 2009
March 20, 2009
Mar. 20, 2009
Mar 20 2009
20 Mar 2009
20 March 2009
20 Mar. 2009
20 March, 2009
Mar 20th, 2009
Mar 21st, 2009
Mar 22nd, 2009
Feb 2009
Sep 2009
Oct 2010
02/01/2009
09/01/2009
6/2008
12/2009
06/01/2008
2009
2010
01/01/2009
01/01/2010
Feb 1977
Sep 2007
May 2012
</code>```

Explanation

Match either of the following options

\d+/\d+(?:/\d+)? Match one or more digits followed by / followed by one or more digits, followed by the possibility of another / with one or more digits

(?:\d+ )?(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[.,]?(?:-\d+-\d+| \d+(?:th|rd|st|nd)?,? \d+| \d+) Match a possibility of one or more digits followed by a space, followed by month names (or their short forms), followed by the possibility of a dot . or comma ,, followed by either - digits - digits; or space  digits with the possibility of th, rd, st, or nd and the possibility of a following comma, then a space and more digits; or a space followed by a digit

\d{4} Match any digit 4 times (this is for single years, but may catch other valid numbers, you may need to change this to your needs. Adding word boundaries as \b\d{4}\b might be a good first step.

Body:
I have a task to extract a wide variety of dates from a text file using Python.

As per the requirements, the following date formats must be properly extracted from the text file:

04/20/2009; 04/20/09; 4/20/09; 4/3/09

Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;

20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009

Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009

Feb 2009; Sep 2009; Oct 2010 (shall be parsed to 02/01/2009, 09/01/2009 etc)

6/2008; 12/2009 (shall be parsed to 06/01/2008 etc).

2009; 2010 (shall be parsed to 01/01/2009 and 01/01/2010)

Regex to the rescue!

Came up with the following expression:

(((0?[1-9]|1[0-2])((\/)|(-)))?(((0?[1-9]|[1-2][0-9]|3[0-1])((\/)|(-))))((19[0-9][0-9])|(20[0-1]{1}[0-9])|([0-9][0-9]))|((19[0-9][0-9])|(20[0-1]{1}[0-9])))|((0[1-9])|(1[0-9])|(2[0-9])|(3[0-1]))?(\D)?(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)((\s|\.|-)((19[0-9][0-9])|(20[0-9][0-9])))

I was able to debug it with Regex101 for all use cases.

However, when I try to run it over a Pandas dataframe using the code below, no matches are found for some of the cases - ("df" stands for a Pandas dataframe where each of the rows contains raw text with a date in one of the formats above)

import re

pattern = '(((0?[1-9]|1[0-2])((\/)|(-)))?(((0?[1-9]|[1-2][0-9]|3[0-1])((\/)|(-))))((19[0-9][0-9])|(20[0-1]{1}[0-9])|([0-9][0-9]))|((19[0-9][0-9])|(20[0-1]{1}[0-9])))|((0[1-9])|(1[0-9])|(2[0-9])|(3[0-1]))?(\D)?(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)((\s|\.|-)((19[0-9][0-9])|(20[0-9][0-9])))'

flags = re.IGNORECASE

m = df.str.extract(pattern, flags)

Cases where there's not a match include:

AFeb 1977: Symmes Hospital\n

"NV fire fighter died Sep 2007 while working.  Was friend from deployment to San Marino and trainings for years prior.  Still troubling to pt.  Didn't go to his funeral.  Spiritual/Religion:\n

's Cathy Bowers is a 50 yo single Caucasian female who presents to the ANH Eating Disorders Department for an evaluation and treatment recommendations for low weight.  She shared that she has recently lost a great deal of weight and is having difficulty meeting her calorie needs due to difficulties with gagging/swallowing, and aversions to specific food textures.  Specifically, since May 2012, she has lost 18 lbs, going from 128 lbs (BMI = 19.5, normal range) to 110.2 lbs (BMI = 16.8, underweight range) at a height of 5\'8" tall.  She has had amenorrhea for 2 months.  Her current weight is her lowest since high school, when she was a model and weighed 98 lbs (BMI = 14.9, underweight range).  At that time, she had amenorrhea, felt pressure to be thin in order to keep her job, and most likely met criteria for frank anorexia nervosa nervosa-restricting type.\n'

For all of these cases, I was able to properly debug the expression and validate them on Reg101.

This makes me think that maybe there's a mismatch between the Python parser/version used by Reg101 and the Python version I'm using (3) - or maybe a parameter that I'm not aware of.

Anyone has a clue?

Thanks in advance!

Body:
Code

See regex in use here

\d+/\d+(?:/\d+)?|(?:\d+ )?(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[.,]?(?:-\d+-\d+| \d+(?:th|rd|st|nd)?,? \d+| \d+)|\d{4}

Results

Input

04/20/2009; 04/20/09; 4/20/09; 4/3/09 Mar-20-2009; Mar 20, 2009; March
  20, 2009; Mar. 20, 2009; Mar 20 2009; 20 Mar 2009; 20 March 2009; 20
  Mar. 2009; 20 March, 2009 Mar 20th, 2009; Mar 21st, 2009; Mar 22nd,
  2009 Feb 2009; Sep 2009; Oct 2010 (shall be parsed to 02/01/2009,
  09/01/2009 etc) 6/2008; 12/2009 (shall be parsed to 06/01/2008 etc).
  2009; 2010 (shall be parsed to 01/01/2009 and 01/01/2010) AFeb 1977:
  Symmes Hospital\n NV fire fighter died Sep 2007 while working. Was
  friend from deployment to San Marino and trainings for years prior.
  Still troubling to pt. Didn't go to his funeral. Spiritual/Religion:
  's Cathy Bowers is a 50 yo single Caucasian female who presents to the
  ANH Eating Disorders Department for an evaluation and treatment
  recommendations for low weight. She shared that she has recently lost
  a great deal of weight and is having difficulty meeting her calorie
  needs due to difficulties with gagging/swallowing, and aversions to
  specific food textures. Specifically, since May 2012, she has lost 18
  lbs, going from 128 lbs (BMI = 19.5, normal range) to 110.2 lbs (BMI =
  16.8, underweight range) at a height of 5\'8" tall. She has had amenorrhea for 2 months. Her current weight is her lowest since high
  school, when she was a model and weighed 98 lbs (BMI = 14.9,
  underweight range). At that time, she had amenorrhea, felt pressure to
  be thin in order to keep her job, and most likely met criteria for
  frank anorexia nervosa nervosa-restricting type.

Output

Below shows matches only.

04/20/2009
04/20/09
4/20/09
4/3/09
Mar-20-2009
Mar 20, 2009
March 20, 2009
Mar. 20, 2009
Mar 20 2009
20 Mar 2009
20 March 2009
20 Mar. 2009
20 March, 2009
Mar 20th, 2009
Mar 21st, 2009
Mar 22nd, 2009
Feb 2009
Sep 2009
Oct 2010
02/01/2009
09/01/2009
6/2008
12/2009
06/01/2008
2009
2010
01/01/2009
01/01/2010
Feb 1977
Sep 2007
May 2012

Explanation

Match either of the following options

\d+/\d+(?:/\d+)? Match one or more digits followed by / followed by one or more digits, followed by the possibility of another / with one or more digits

(?:\d+ )?(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[.,]?(?:-\d+-\d+| \d+(?:th|rd|st|nd)?,? \d+| \d+) Match a possibility of one or more digits followed by a space, followed by month names (or their short forms), followed by the possibility of a dot . or comma ,, followed by either - digits - digits; or space  digits with the possibility of th, rd, st, or nd and the possibility of a following comma, then a space and more digits; or a space followed by a digit

\d{4} Match any digit 4 times (this is for single years, but may catch other valid numbers, you may need to change this to your needs. Adding word boundaries as \b\d{4}\b might be a good first step.


问:
how can I create executable file for the program written on Java?
everyone, how can I create executable file for the program written on Java in Eclipse Helios? I mean to create small icon to be able start program only by double-clicking on its icon, thanks in advance
edited
I mean executable for Windows

答: The best answer for this situation is to launch the app. using Java Web Start.  JWS can not only create desktop and start menu launch items, but provides automatic updates, cross-platform compatibility and much more.</p>


问:
+= operator on a float return an empty numpy array instead of throwing TypeError
Let's say if I want to iteratively append floats to a list L, I can use L.append in a for loop. I was messing around with the operator += (which I take it as L.extend) and did the following:

```<code>from sklearn.linear_model import LinearRegression
import numpy as np

def calculate_R2(X,y):
    reg = LinearRegression()
    reg.fit(X,y)
    score = reg.score(X,y)

    return score

y = [1,2,3]

score = []
for ind in range(10):
    X = np.random.rand(3,1)
    score+=calculate_R2(X,y)
</code>```

Since calculate_R2(X,y) returns a float, I would expect the first iteration of the for loop would fail and throw a TypeError that a float object is not iterable. However, the script runs without error, and returns score as

array([], dtype=float64)

Now, I just dont understand why this happens. If I replace the function calculate_R2(X,y) by another function add(x), the script does throw the correct error message (TypeError: 'int' object is not iterable):

```<code>def add(x):
    return x+10

score = []
for ind in range(10):
    score+=add(ind)
</code>```

I am using python 2.7 and sklearn version 0.18.1 on Spyder. Any thoughts would be appreciated!

答:
Python list + Python int or float

During the first iteration, your score variable is a plain Python list. You're right, adding an int or a float would fail with a TypeError:

```<code>>>> [1, 2, 3] + 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
</code>```

Python list + np.float

calculate_R2 returns a numpy.float64. Adding a numpy.float64 to a Python list adds the float to every element and returns a np.array:

```<code>>>> import numpy as np
>>> [1, 2, 3] + np.float64(3.14)
array([ 4.14,  5.14,  6.14])
</code>```

BTW, you shouldn't use the same variable name for two distinct object. Your collection of scores could be called scores.

np.array + scalar

Adding a scalar to a numpy array doesn't append anything. It adds the scalar to every element of the array:

```<code>>>> import numpy as np
>>> np.array([1, 2, 3]) + 1
array([2, 3, 4])
</code>```

If you do it on an empty array, it adds the scalar to every element of the empty array, and returns the corresponding array:

```<code>>>> np.array([]) + 1
array([], dtype=float64)
</code>```

Body:
Let's say if I want to iteratively append floats to a list L, I can use L.append in a for loop. I was messing around with the operator += (which I take it as L.extend) and did the following:

from sklearn.linear_model import LinearRegression
import numpy as np

def calculate_R2(X,y):
    reg = LinearRegression()
    reg.fit(X,y)
    score = reg.score(X,y)

    return score

y = [1,2,3]

score = []
for ind in range(10):
    X = np.random.rand(3,1)
    score+=calculate_R2(X,y)

Since calculate_R2(X,y) returns a float, I would expect the first iteration of the for loop would fail and throw a TypeError that a float object is not iterable. However, the script runs without error, and returns score as

array([], dtype=float64)

Now, I just dont understand why this happens. If I replace the function calculate_R2(X,y) by another function add(x), the script does throw the correct error message (TypeError: 'int' object is not iterable):

def add(x):
    return x+10

score = []
for ind in range(10):
    score+=add(ind)

I am using python 2.7 and sklearn version 0.18.1 on Spyder. Any thoughts would be appreciated!

Body:
Python list + Python int or float

During the first iteration, your score variable is a plain Python list. You're right, adding an int or a float would fail with a TypeError:

>>> [1, 2, 3] + 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list

Python list + np.float

calculate_R2 returns a numpy.float64. Adding a numpy.float64 to a Python list adds the float to every element and returns a np.array:

>>> import numpy as np
>>> [1, 2, 3] + np.float64(3.14)
array([ 4.14,  5.14,  6.14])

BTW, you shouldn't use the same variable name for two distinct object. Your collection of scores could be called scores.

np.array + scalar

Adding a scalar to a numpy array doesn't append anything. It adds the scalar to every element of the array:

>>> import numpy as np
>>> np.array([1, 2, 3]) + 1
array([2, 3, 4])

If you do it on an empty array, it adds the scalar to every element of the empty array, and returns the corresponding array:

>>> np.array([]) + 1
array([], dtype=float64)


问:
How to access inputs attributes in node js?
Or simpler, how do I implement an equivalent of the code below in node js?

```<code>selectedRadio = document.querySelector('input[name="device"]:checked').dataset.name;
</code>```

I'm using Node js for backend of an app with Express.js and BodyParser.

I was able to access HTML elements with their Names with req.body.elementName, but I have trouble getting value from the code above.

答:
The DOM doesn't exist in Node. There is no body or document because there is no website in the backend. That means accessing a DOM element by document.querySelector() will not work because document doesn't exist.

You should be passing the values directly to your Node application, instead of passing HTML Elements.

Body:
Or simpler, how do I implement an equivalent of the code below in node js?

selectedRadio = document.querySelector('input[name="device"]:checked').dataset.name;

I'm using Node js for backend of an app with Express.js and BodyParser.

I was able to access HTML elements with their Names with req.body.elementName, but I have trouble getting value from the code above.