问:
JS Regex to find href of several a tags
I need a regex to find the contents of the hrefs from these a tags :

```<code><p class="bc_shirt_delete">
   <a href="/CustomContentProcess.aspx?CCID=13524&OID=3936923&A=Delete" onclick="javascript:return confirm('Are You sure you want to delete this item?')">delete</a>
</p>
</code>```

Just the urls, not the href/ tags.

I'm parsing a plain text ajax request here, so I need a regex.

答:
It's important to be non-greedy. And to cater for —matching— ' or "

```<code>test = "<a href="#" class="foo bar"> banana
        <a href='http://google.de/foo?yes=1&no=2' data-href='foobar'/>"

test.replace(/href=(?:\'.*?\'|\".*?\")/gi,'');
</code>```

disclaimer: The one thing it does not catch is html5 attribs data-href...

Title: JS Regex to find href of several a tags

Body:
I need a regex to find the contents of the hrefs from these a tags :

   delete

Just the urls, not the href/ tags.

I'm parsing a plain text ajax request here, so I need a regex.

Body:
It's important to be non-greedy. And to cater for —matching— ' or "

test = "<a href="#" class="foo bar"> banana
        <a href='http://google.de/foo?yes=1&no=2' data-href='foobar'/>"

test.replace(/href=(?:\'.*?\'|\".*?\")/gi,'');

disclaimer: The one thing it does not catch is html5 attribs data-href...


来源: stackexchange

问:
GTMetrix Wordpress Speed issue
I am trying to reduce the load time for my website using GTMetrix. I find below references from my site. But I am not able to find the source.

I checked themes and plugins as well and came to conclusion its some unwanted code or spam.

```<code>https://cdn.atlassbx.com/FB/11122200772940/browser_features1488235112.js
https://cdn.atlassbx.com/FB/11122200773193/atlas_tots1480453070.js
https://cdn.atlassbx.com/FB/11237204735744/PerspectiveTransform.min.js
https://cdn.atlassbx.com/FB/11237204735744/banner.js
https://cdn.atlassbx.com/FB/11237204735744/bannerboy.min.js
https://cdn.atlassbx.com/FB/11237204735744/content.jpg
https://cdn.atlassbx.com/FB/11237204735744/cta_txt.png
https://cdn.atlassbx.com/FB/11237204735744/image_1.jpg
https://cdn.atlassbx.com/FB/11237204735744/image_2.png
https://cdn.atlassbx.com/FB/11237204735744/logo_squarespace.png
https://cdn.atlassbx.com/FB/11237204735744/settings.js
https://cdn.atlassbx.com/FB/11237204735744/txt_0_1.png
https://cdn.atlassbx.com/FB/11237204735744/txt_0_2.png
https://cdn.atlassbx.com/FB/11237204735744/txt_0_3.png
https://cdn.atlassbx.com/FB/11237204735744/txt_1_1.png
https://cdn.atlassbx.com/FB/11237204735744/txt_2_1.png
https://cdn.atlassbx.com/FB/11237205062003/GothamSSm-Book.woff
https://cdn.atlassbx.com/FB/11237205062003/GothamSSm-Light.woff
https://cdn.atlassbx.com/FB/11237205062003/banner.min.js
https://cdn.atlassbx.com/FB/11237205062003/bg.jpg
https://cdn.atlassbx.com/FB/11237205062003/bg_blurred.jpg
https://cdn.atlassbx.com/FB/11237205062003/handPointer.png
https://cdn.atlassbx.com/FB/11237205062003/icon_cart.png
https://cdn.atlassbx.com/FB/11237205062003/icon_check.png
https://cdn.atlassbx.com/FB/11237205062003/icon_close.png
https://cdn.atlassbx.com/FB/11237205062003/logo_squarespace.png
https://cdn.atlassbx.com/FB/11237205062003/mousePointer.png
https://cdn.atlassbx.com/FB/11237205062003/txt_cta.png
https://cdn.atlassbx.com/FB/11237205062003/txt_cta_hover.png
https://cdn.atlassbx.com/FB/11237205062003/txt_endframe.png
</code>```

https://gtmetrix.com/reports/projectsgeek.com/G3QsoTpO

Please help

答: For wordpress and speed you need to install a cache plugin like wp total cache, also you need to enable G-zip compression server side</p>

ContentLicense: CC BY-SA 3.0

Title: GTMetrix Wordpress Speed issue

Body:
I am trying to reduce the load time for my website using GTMetrix. I find below references from my site. But I am not able to find the source.

I checked themes and plugins as well and came to conclusion its some unwanted code or spam.

https://cdn.atlassbx.com/FB/11122200772940/browser_features1488235112.js
https://cdn.atlassbx.com/FB/11122200773193/atlas_tots1480453070.js
https://cdn.atlassbx.com/FB/11237204735744/PerspectiveTransform.min.js
https://cdn.atlassbx.com/FB/11237204735744/banner.js
https://cdn.atlassbx.com/FB/11237204735744/bannerboy.min.js
https://cdn.atlassbx.com/FB/11237204735744/content.jpg
https://cdn.atlassbx.com/FB/11237204735744/cta_txt.png
https://cdn.atlassbx.com/FB/11237204735744/image_1.jpg
https://cdn.atlassbx.com/FB/11237204735744/image_2.png
https://cdn.atlassbx.com/FB/11237204735744/logo_squarespace.png
https://cdn.atlassbx.com/FB/11237204735744/settings.js
https://cdn.atlassbx.com/FB/11237204735744/txt_0_1.png
https://cdn.atlassbx.com/FB/11237204735744/txt_0_2.png
https://cdn.atlassbx.com/FB/11237204735744/txt_0_3.png
https://cdn.atlassbx.com/FB/11237204735744/txt_1_1.png
https://cdn.atlassbx.com/FB/11237204735744/txt_2_1.png
https://cdn.atlassbx.com/FB/11237205062003/GothamSSm-Book.woff
https://cdn.atlassbx.com/FB/11237205062003/GothamSSm-Light.woff
https://cdn.atlassbx.com/FB/11237205062003/banner.min.js
https://cdn.atlassbx.com/FB/11237205062003/bg.jpg
https://cdn.atlassbx.com/FB/11237205062003/bg_blurred.jpg
https://cdn.atlassbx.com/FB/11237205062003/handPointer.png
https://cdn.atlassbx.com/FB/11237205062003/icon_cart.png
https://cdn.atlassbx.com/FB/11237205062003/icon_check.png
https://cdn.atlassbx.com/FB/11237205062003/icon_close.png
https://cdn.atlassbx.com/FB/11237205062003/logo_squarespace.png
https://cdn.atlassbx.com/FB/11237205062003/mousePointer.png
https://cdn.atlassbx.com/FB/11237205062003/txt_cta.png
https://cdn.atlassbx.com/FB/11237205062003/txt_cta_hover.png
https://cdn.atlassbx.com/FB/11237205062003/txt_endframe.png

https://gtmetrix.com/reports/projectsgeek.com/G3QsoTpO

Please help


问:
How to stop `mail` action sending to `:to` address if :bcc addresses are empty in ActionMailer?
I have a actinmailer method where the @receiver is populated if it matches certain conditions and there is a @default_mail. Which sends mails to receivers in BCC and default_mail in to field. It is as follows:

```<code>def mail_users
    @default_mail = "user@gmail.com"
    @latest_listing_mail= Equipment.joins(:user).last.user.email
    @wanted_req_mail = WantedEquipment.where(sub_category_id: "#{a}", status: 2).pluck(:email)
    @wanted_req_mail.include? @latest_listing_mail
    if true
       @receiver = @wanted_req_mail.delete(@latest_listing_mail)
       @receiver = @wanted_req_mail
       mail(bcc: @receiver, to: @default_mail)
    end
end
</code>```

I don't want the mail to perform if the @receiver is empty. How do I achieve this?

答:
Just add a condition

```<code>mail(bcc: @receiver, to: @default_mail) if @receiver.present?
</code>```

And you might want to remove this condition

```<code>if true # doesn't make sense
end
</code>```

Body:
I have a actinmailer method where the @receiver is populated if it matches certain conditions and there is a @default_mail. Which sends mails to receivers in BCC and default_mail in to field. It is as follows:

def mail_users
    @default_mail = "user@gmail.com"
    @latest_listing_mail= Equipment.joins(:user).last.user.email
    @wanted_req_mail = WantedEquipment.where(sub_category_id: "#{a}", status: 2).pluck(:email)
    @wanted_req_mail.include? @latest_listing_mail
    if true
       @receiver = @wanted_req_mail.delete(@latest_listing_mail)
       @receiver = @wanted_req_mail
       mail(bcc: @receiver, to: @default_mail)
    end
end

I don't want the mail to perform if the @receiver is empty. How do I achieve this?

Body:
Just add a condition

mail(bcc: @receiver, to: @default_mail) if @receiver.present?

And you might want to remove this condition

if true # doesn't make sense
end


问:
ASP.NET Core 1.1 web application does not start when running with IIS Express in Visual Studio 2017
I've recently installed Visual Studio 2017 Professional and have just created the boilerplate ASP.NET Core Web Application

This is what happens when I hit Run (With IIS Express):

And this is what Visual Studio 2017's Output window says:

The program '[8260] dotnet.exe' has exited with code -2147450749
  (0x80008083).

The program '[6476] iisexpress.exe' has exited with code 0 (0x0).

Steps to fix?

答:
Okay, this worked for me: Install the x86 SDK...

https://www.microsoft.com/net/download/core


问:
Get All Photos from Facebook
I need to get user uploaded and tagged photos from facebook account using graph API.

I tried following code but it's give nothing to me .

```<code> GraphRequest request = GraphRequest.newMeRequest(
                                        token,
                                        new GraphRequest.GraphJSONObjectCallback() {
                                            @Override
                                            public void onCompleted(JSONObject object, GraphResponse response) {
                                                // Insert your code here

                                            Log.e("Hi "," "+response.getJSONObject().toString());

                                            }
                                        });

                              GraphRequest req = GraphRequest.newGraphPathRequest(token, "me/photos",  callback);
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, name");
            req.setParameters(parameters);
            req.executeAsync();
</code>```

I have given following permission to facbook.

```<code>loginButton.setReadPermissions(Arrays.asList("public_profile","user_photos"));
</code>```

Thanks

答:
Use this API</p>

```<code>json.FB_URL+json.PAGE_ID+"?fields=albums.limit(30)%7Bname%2Cid%2Cdescription%2Cpicture%7D&access_token="+json.ACCESS_TOKEN
</code>```

Title: Get All Photos from Facebook

Body:
I need to get user uploaded and tagged photos from facebook account using graph API.

I tried following code but it's give nothing to me .

 GraphRequest request = GraphRequest.newMeRequest(
                                        token,
                                        new GraphRequest.GraphJSONObjectCallback() {
                                            @Override
                                            public void onCompleted(JSONObject object, GraphResponse response) {
                                                // Insert your code here

                                            Log.e("Hi "," "+response.getJSONObject().toString());

                                            }
                                        });

                              GraphRequest req = GraphRequest.newGraphPathRequest(token, "me/photos",  callback);
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, name");
            req.setParameters(parameters);
            req.executeAsync();

I have given following permission to facbook.

loginButton.setReadPermissions(Arrays.asList("public_profile","user_photos"));

Thanks

Body:
Use this API

json.FB_URL+json.PAGE_ID+"?fields=albums.limit(30)%7Bname%2Cid%2Cdescription%2Cpicture%7D&access_token="+json.ACCESS_TOKEN


问:
Datatable getting misaligned, when changing page after scrolling down a little bit
When i change the page without scrolling down vertically on current page, other page is loaded properly.
but when i change page after scrolling down somewhat, then DataTable gets misaligned
Although this misaligned dataTable gets aligned if i search something, but i do not want the datatable to get misaligned in the first place on the change of page

This is my configuration
dTable = $("table.list").dataTable({
                    "iDisplayLength": 100,
                    "fixedHeader":true,
                    "sScrollX": "100%",
                    "sScrollY": "440px",
                    "aaSorting": [[3,'asc']],
                    "columns": [
                                null,null,null,null,null,
                                { "orderDataType": "dom-text-numeric" },
                                { "orderDataType": "dom-text", type: 'string' },{ "orderDataType": "dom-text", type: 'string' },
                                { "orderDataType": "dom-select" },{ "orderDataType": "dom-text", type: 'string' },
                                { "orderDataType": "dom-text", type: 'string' },{ "orderDataType": "dom-text", type: 'string' },
                                { "orderDataType": "dom-text", type: 'string' },{ "orderDataType": "dom-text", type: 'string' },
                                { "orderDataType": "dom-text", type: 'string' },{ "orderDataType": "dom-text", type: 'string' }
                            ],
                    "columnDefs": [
                                    { "type": "num-html", targets: 4 },
                                    { "type": "num-html", targets: 5 }
                                ],
                    "fixedColumns":{
                        leftColumns: 4
                    },
                    "autoWidth":true,
                    'responsive':true
                });

答:
I do not the cause of the bug, but the solution or hack which helped me is
dTable.on("page.dt",handlePageChange);
function handlePageChange(){
 document.querySelector(".dataTables_scroll div.dataTables_scrollBody").scrollTop=0;
}

Explanation:

1. This function will be called before changing the page in datatable, and on click of pagination buttons

2. before changing page, make the scrollTop of the dataTable body = 0;


问:
How to scale to certain element in a iframe responsive?
I've tried several ways to scale to HTML-element within the iframe which opening not on same domain

It`s works fine with wrapped div which has transform scale attribute

```<code><div class="wrapper">
    <iframe class="scaled" src="frame.html" scrolling="no" frameborder="0"></iframe>
</div>
.wrapper {
    position: absolute;
    width:100%;
    height: 100%;
    top: 0px;
    left: 0px;
    overflow: hidden;
    transform: scale(4,33) translateY(-107px) translateX(-240px);
}

iframe.scaled {
    overflow: hidden;
    width: 1920px;
    height: 1080px;
}
</code>```

My question is how i can make this responsive? that the scaling was the same on all devices (mobile), i guess we need some javascript code to do this?

答:
I think the best solution is to use pure HTML.

The purpose of this code is to set bottom padding to the aspect ratio of the video or iframe. The iframe is then scaled to 100%, in both width and height, which completely fills the outer container. The outer container is now able to atuomatically adjust it's height according to it's width and the iframe adjust accordingly.

```

JsFiddle:

https://jsfiddle.net/4Lmjb3ge/

I hope this answers your question.

Body:
I've tried several ways to scale to HTML-element within the iframe which opening not on same domain

It`s works fine with wrapped div which has transform scale attribute

.wrapper {
    position: absolute;
    width:100%;
    height: 100%;
    top: 0px;
    left: 0px;
    overflow: hidden;
    transform: scale(4,33) translateY(-107px) translateX(-240px);
}

iframe.scaled {
    overflow: hidden;
    width: 1920px;
    height: 1080px;
}

My question is how i can make this responsive? that the scaling was the same on all devices (mobile), i guess we need some javascript code to do this?

Body:
I think the best solution is to use pure HTML.

The purpose of this code is to set bottom padding to the aspect ratio of the video or iframe. The iframe is then scaled to 100%, in both width and height, which completely fills the outer container. The outer container is now able to atuomatically adjust it's height according to it's width and the iframe adjust accordingly.

<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
    <iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
        src="https://www.w3schools.com/html/">
    </iframe>
</div>

JsFiddle:

https://jsfiddle.net/4Lmjb3ge/

I hope this answers your question.


问:
Text correction Damereau Levenshtein python
I want to correct a text by using Damereau Levenshtein python (because it also considers transposition). I need to replace all the words of my input text by the words in a dictionary that have a distance of 1. How can I do this ?

Is there another way to correct automatically spelling mistakes ?

Thanks everyone

答:
Well, there exists a ready-made Python package to solve your problem.
I think the method distance(string1, string2) should at least solve half your problem.


问:
Intellisense in Visual Studio Code for Object pascal with reference into c# compiled dll
There is my problem: I´m trying to use Intellisense in Visual Studio Code in Object pascal language, where some of the main classes are in the C# Dll library a I´m using OmniPascal Extension. Is there any chance to get a reference to this Dll (like in Visual Studio) so the intellisense could start working? Or is there another way?

答:
There is no way to get the symbols from the C# DLL to appear in OmniPascal's code completion automatically.
You need to declare the DLL's interfaces in one or more .pas files. OmniPascal will add their interfaces to code completion when you add these units to the uses clauses.

ContentLicense: CC BY-SA 4.0


问:
Docker: Download all from nltk in Dockerfile
How would I achieve the following in a Dockerfile:</p>

```<code>sudo python
import nltk
nltk.download('all')
</code>```

答:
You can build a custom Docker image with everything you need:

```<code>FROM python:3.6-slim
RUN pip3 install nltk
RUN [ "python", "-c", "import nltk; nltk.download('all')" ]
ENTRYPOINT python
</code>```

Then build:

```<code>docker build -t docker-nltk .
</code>```

And run:

```<code>docker run -it docker-nltk
</code>```

Body:
How would I achieve the following in a Dockerfile:

sudo python
import nltk
nltk.download('all')

Body:
You can build a custom Docker image with everything you need:

FROM python:3.6-slim
RUN pip3 install nltk
RUN [ "python", "-c", "import nltk; nltk.download('all')" ]
ENTRYPOINT python

Then build:

docker build -t docker-nltk .

And run:

docker run -it docker-nltk


问:
Variable is not defined - VueJS
I would like to ask, on why the variable title is getting an undefined error even though there's a value on it. Here's my code so far:

```<code>   <div class="echelon-main-container" id="test-app">
        <test-empower></test-empower>
        <script type="x-template" id="test-empower">
            <section class="test-empower" id="test-empower">
                <h2 class="header-title">{{ title }}</h2>
                <h2 class="header-subtitle">{{ description }}</h2>
            </section>
        </script>
    </div>

Vue.component('echelon-empower', {
    template: '#echelon-empower',
    data: function() {
        return {
            title: "AT ECHELON",
            description: "Empowering Entrepreneurs to build and grow their companies since 2009"
        }
    }
});

Vue.component('echelon-about', {
    template: '#echelon-about'
});

Vue.component('echelon-who-attends',{
    template: '#echelon-who-attends'
});

Vue.component('echelon-highlights', {
    template: '#echelon-highlights'
});

new Vue({
    el: "#echelon-app"
});
</code>```

答:
The below html which has an id of #test-app derives its vue-instance properties from the new Vue(...) part of the code. Which really doesn't have title and hence the error.

```<code><div class="echelon-main-container" id="test-app">
    <test-empower></test-empower>
    <script type="x-template" id="test-empower">
        <section class="test-empower" id="test-empower">
            <h2 class="header-title">{{ title }}</h2>
            <h2 class="header-subtitle">{{ description }}</h2>
        </section>
    </script>
</div>
</code>```

The el property in the new Vue(...) specifies the mount point for the new Vue() instance you are creating.

In the Vue.component(...):

```<code>Vue.component('test-empower', {
  template: '#test-empower'
});
</code>```

#test-empower is not the mount point as you are expecting. It is the template this component must use when <test-empower> is used in your application.

As per the edit, you need to separate out your templates to resolve your need of having separate properties like in this fiddle.

Title: Variable is not defined - VueJS

Body:
I would like to ask, on why the variable title is getting an undefined error even though there's a value on it. Here's my code so far:

        <test-empower></test-empower>

Vue.component('echelon-empower', {
    template: '#echelon-empower',
    data: function() {
        return {
            title: "AT ECHELON",
            description: "Empowering Entrepreneurs to build and grow their companies since 2009"
        }
    }
});

Vue.component('echelon-about', {
    template: '#echelon-about'
});

Vue.component('echelon-who-attends',{
    template: '#echelon-who-attends'
});

Vue.component('echelon-highlights', {
    template: '#echelon-highlights'
});

new Vue({
    el: "#echelon-app"
});

Body:
The below html which has an id of #test-app derives its vue-instance properties from the new Vue(...) part of the code. Which really doesn't have title and hence the error.

<div class="echelon-main-container" id="test-app">
    <test-empower></test-empower>
    <script type="x-template" id="test-empower">
        <section class="test-empower" id="test-empower">
            <h2 class="header-title">{{ title }}</h2>
            <h2 class="header-subtitle">{{ description }}</h2>
        </section>
    </script>
</div>

The el property in the new Vue(...) specifies the mount point for the new Vue() instance you are creating.

In the Vue.component(...):

Vue.component('test-empower', {
  template: '#test-empower'
});

#test-empower is not the mount point as you are expecting. It is the template this component must use when <test-empower> is used in your application.

As per the edit, you need to separate out your templates to resolve your need of having separate properties like in this fiddle.


问:
How can I run a windows batch file but hide the command window?
How can I run a windows batch file but hiding the command window? I dont want cmd.exe to be visible on screen when the file is being executed. Is this possible?</p>

答:
1,Download the bat to exe converter and install it
2,Run the bat to exe application
3,Download .pco images if you want to make good looking exe
4,specify the bat file location(c:\my.bat)
5,Specify the location for saving the exe(ex:c:/my.exe)
6,Select Version Information Tab
7,Choose the icon file (downloaded .pco image)
8,if you want fill the information like version,comapny name etc
9,change the tab to option
10,Select the invisible application(This will hide the command prompt while running the application)
11,Choose 32 bit(if you select 64 bit exe will work only in 32 bit OS)
12,Compile
13,Copy the exe to the location where bat file executed properly
14,Run the exe</p>

ContentLicense: CC BY-SA 2.5


问:
Equivalent of two table() functions in dplyr
I have a column with two variables that I would like to count occurrences of by date.

```<code>> testData
   plan_type       date
1 subscriber 2016-09-06
2 subscriber 2017-01-19
3 subscriber 2016-10-07
4        PPU 2017-01-19
5        PPU 2015-06-17
6        PPU 2015-07-03
</code>```

I know that this can be done for example by subsetting into two different dataframes - one with only subscriber and one with only PPU data, then use table() and bind the two dataframes together. But I'd like to find a more efficient solution with dplyr that can do this in one command.

The output should look something like this, with NA values where there is no data for one of the variables.

```<code>> output
        date subscriber  PPU
1 2015-06-17       <NA>    1
2 2015-07-03       <NA>    1
3 2016-09-06          1 <NA>
4 2016-10-07          1 <NA>
5 2017-01-19          1    1
</code>```

Is there a specific formula that would perform this function in dplyr?

答:
With dplyr you can create a new costant columns n and then spread():

library(dplyr)
library(tidyr)

df %>%
    mutate(n = 1) %>%
    spread(plan_type, n)

#>         date PPU subscriber
#> 1 2015-06-17   1         NA
#> 2 2015-07-03   1         NA
#> 3 2016-09-06  NA          1
#> 4 2016-10-07  NA          1
#> 5 2017-01-19   1          1
```

<p>Data:</p>

<pre class="lang-r prettyprint-override"><code>df <- read.table(text = '   plan_type       date
                 1 subscriber 2016-09-06
                 2 subscriber 2017-01-19
                 3 subscriber 2016-10-07
                 4        PPU 2017-01-19
                 5        PPU 2015-06-17
                 6        PPU 2015-07-03', header = T)
</code>```

Body:
I have a column with two variables that I would like to count occurrences of by date.

> testData
   plan_type       date
1 subscriber 2016-09-06
2 subscriber 2017-01-19
3 subscriber 2016-10-07
4        PPU 2017-01-19
5        PPU 2015-06-17
6        PPU 2015-07-03

I know that this can be done for example by subsetting into two different dataframes - one with only subscriber and one with only PPU data, then use table() and bind the two dataframes together. But I'd like to find a more efficient solution with dplyr that can do this in one command.

The output should look something like this, with NA values where there is no data for one of the variables.

> output
        date subscriber  PPU
1 2015-06-17       <NA>    1
2 2015-07-03       <NA>    1
3 2016-09-06          1 <NA>
4 2016-10-07          1 <NA>
5 2017-01-19          1    1

Is there a specific formula that would perform this function in dplyr?

Body:
With dplyr you can create a new costant columns n and then spread():

library(dplyr)
library(tidyr)

df %>%
    mutate(n = 1) %>%
    spread(plan_type, n)

#>         date PPU subscriber
#> 1 2015-06-17   1         NA
#> 2 2015-07-03   1         NA
#> 3 2016-09-06  NA          1
#> 4 2016-10-07  NA          1
#> 5 2017-01-19   1          1

Data:

df <- read.table(text = '   plan_type       date
                 1 subscriber 2016-09-06
                 2 subscriber 2017-01-19
                 3 subscriber 2016-10-07
                 4        PPU 2017-01-19
                 5        PPU 2015-06-17
                 6        PPU 2015-07-03', header = T)


问:
awk split and drop column but something wrong with substr part
I have an awk code to split a file by columns and print out the output to a new file name.

```<code>awk -F"|" 'NR==1 {h=substr($0, index($0,$5)); next}
            {file= path ""$1""$2"_"$3"_"$4"_03042017.csv"; print (a[file]++?"": "DM9 03042017" ORS h ORS) substr($0, index($0,$5)) > file}
             END{for(file in a) print "EOF " a[file] > file}'
</code>```

As I use substr ($0, index($0,$5) so the new output will only have data start at fifth column and the rest. It works fine except when the input data I have got the same value.

For example,

```<code>product | ID | Branch | Office | Type | ....
ABC     | 12 | KL     |  GH    |  Z   | ....
</code>```

For the above example, the code works well as the data input is different.

```<code>product | ID | Branch | Office | Type | ....
ABC     | 12 | KK     |  KK    |  Z   | ....
</code>```

But if I have data input like second example, I have the same value data for third and fourth columns, the code doesn't work well. Instead of getting output start and fifth column and more, I got the result at third column and more.

So, I suspect because as the data input for third and fourth are the same, so it stopped at third line as I used substr.

Is anyone can help me on this matter? Sorry for the long post and appreciate it a lot if you guys can give me some ideas. Thank you.

答:
if structure is fixed like your sample (fixed length field)</p>

```<code>awk -F '[[:blank:]]*[|][[:blank:]]*' -v path="./" '
   NR==1 {
      for( i=1;i<5;i++) $i = ""
      h = $0; sub(/^[[:blank:]|]+/,"", h)
      next
      }

      {
      file= path $1 $2 "_" $3 "_" $4 "_03042017.csv"

      # remove 4 first field
      for( i=1;i<5;i++) $i = ""
      # cleaning starting space
      Cleaned = $0; sub( /^[[:blank:]|]+/, "", Cleaned)

      print ( a[file]++ ? "" : "DM9 03042017" ORS h ORS ) Cleaned > file
      }

   END {
      for(file in a) { print "EOF " a[file] > file }
      }
   ' YourFile
</code>```

Body:
I have an awk code to split a file by columns and print out the output to a new file name.

awk -F"|" 'NR==1 {h=substr($0, index($0,$5)); next}
            {file= path ""$1""$2"_"$3"_"$4"_03042017.csv"; print (a[file]++?"": "DM9 03042017" ORS h ORS) substr($0, index($0,$5)) > file}
             END{for(file in a) print "EOF " a[file] > file}'

As I use substr ($0, index($0,$5) so the new output will only have data start at fifth column and the rest. It works fine except when the input data I have got the same value.

For example,

product | ID | Branch | Office | Type | ....
ABC     | 12 | KL     |  GH    |  Z   | ....

For the above example, the code works well as the data input is different.

product | ID | Branch | Office | Type | ....
ABC     | 12 | KK     |  KK    |  Z   | ....

But if I have data input like second example, I have the same value data for third and fourth columns, the code doesn't work well. Instead of getting output start and fifth column and more, I got the result at third column and more.

So, I suspect because as the data input for third and fourth are the same, so it stopped at third line as I used substr.

Is anyone can help me on this matter? Sorry for the long post and appreciate it a lot if you guys can give me some ideas. Thank you.

Body:
if structure is fixed like your sample (fixed length field)

awk -F '[[:blank:]]*[|][[:blank:]]*' -v path="./" '
   NR==1 {
      for( i=1;i<5;i++) $i = ""
      h = $0; sub(/^[[:blank:]|]+/,"", h)
      next
      }

      {
      file= path $1 $2 "_" $3 "_" $4 "_03042017.csv"

      # remove 4 first field
      for( i=1;i<5;i++) $i = ""
      # cleaning starting space
      Cleaned = $0; sub( /^[[:blank:]|]+/, "", Cleaned)

      print ( a[file]++ ? "" : "DM9 03042017" ORS h ORS ) Cleaned > file
      }

   END {
      for(file in a) { print "EOF " a[file] > file }
      }
   ' YourFile


问:
Django Logging and Session Information
I have tried to google this one to death but could not find the answer, so if someone can point me to the doc or explain how to do this that would be great.

I am trying to include Session information from the Django request (i.e cookies) in all logs, now this is fine in the views etc that have access to the request I can just format that in the message that I am logging.

The issue is with installed packages, these have no knowledge of the session and log without this information and I am yet to find a way to define this in the formatter so that the formatter is more session aware.

I need to do this as I have to send all logs to a syslog server and would like to be able to search the logs for an entire session and get even package level logs.

EDIT:

Sorry guys I am editing the question for a little more clarity.

The overall goal is to wrap all messages that get generated in a api call with the session information this would include any packages that are not directly tied to the Django application itself, this is so that I can search for all logs relating to a session. I hope this makes sense

Thanks

John.

答:
Something like this:

```<code>from django.contrib.sessions.backends.db import SessionStore

s = SessionStore()
# stored as seconds since epoch since datetimes are not serializable in JSON.
s['last_login'] = 1376587691
>>> s.create()
>>> s.session_key
'2b1189a188b44ad18c35e113ac6ceead'
</code>```

Django docs ref: https://docs.djangoproject.com/en/1.10/topics/http/sessions/#using-sessions-out-of-views

Title: Django Logging and Session Information

Body:
Something like this:

from django.contrib.sessions.backends.db import SessionStore

s = SessionStore()
# stored as seconds since epoch since datetimes are not serializable in JSON.
s['last_login'] = 1376587691
>>> s.create()
>>> s.session_key
'2b1189a188b44ad18c35e113ac6ceead'

Django docs ref: https://docs.djangoproject.com/en/1.10/topics/http/sessions/#using-sessions-out-of-views


问:
Fetching records that having their monthly period of creation date
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

```<code>2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec
</code>```

The best simple query I could think of was this:

```<code>SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour
</code>```

But the problem is there are some specific days that will be left out of the query. Such as when

```<code>created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00
</code>```

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

```<code>create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);
</code>```

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

答:
First, let's try to understand your requirements better. You'll need all the records, for which the timestamp column (created_date) & the current time (now()) is in the following relation:

has the exact same hour

AND

has the exact same day

OR

created_date has a day, which is greater than now()'s day

BUT only if now() is in the last day of the current month.

```<code>SELECT *
FROM   mytable
WHERE  EXTRACT(hour FROM created_date) = EXTRACT(hour FROM now())
AND    (EXTRACT(day FROM created_date) = EXTRACT(day  FROM now())
OR      CASE
          WHEN EXTRACT(month FROM CURRENT_DATE + 1) <> EXTRACT(month FROM CURRENT_DATE)
          THEN EXTRACT(day FROM created_date) > EXTRACT(day FROM now())
          ELSE FALSE
        END)
</code>```

http://rextester.com/TXGCSI34243

Note: if you want to bind timestamps for your solution (not actually using the now() & current_date functions) then use WHEN EXTRACT(month FROM ? + INTERVAL '1 day') > EXTRACT(month FROM ?) to test whether the bound timestamp is the last day of its month, or not.

Body:
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec

The best simple query I could think of was this:

SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour

But the problem is there are some specific days that will be left out of the query. Such as when

created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

Body:
First, let's try to understand your requirements better. You'll need all the records, for which the timestamp column (created_date) & the current time (now()) is in the following relation:

has the exact same hour

AND

has the exact same day

OR

created_date has a day, which is greater than now()'s day

BUT only if now() is in the last day of the current month.

SELECT *
FROM   mytable
WHERE  EXTRACT(hour FROM created_date) = EXTRACT(hour FROM now())
AND    (EXTRACT(day FROM created_date) = EXTRACT(day  FROM now())
OR      CASE
          WHEN EXTRACT(month FROM CURRENT_DATE + 1) <> EXTRACT(month FROM CURRENT_DATE)
          THEN EXTRACT(day FROM created_date) > EXTRACT(day FROM now())
          ELSE FALSE
        END)

http://rextester.com/TXGCSI34243

Note: if you want to bind timestamps for your solution (not actually using the now() & current_date functions) then use WHEN EXTRACT(month FROM ? + INTERVAL '1 day') > EXTRACT(month FROM ?) to test whether the bound timestamp is the last day of its month, or not.


问:
Unable to draw a google chart from firebase db
I want to visualize some simple sensor readings stored in firebase in a basic line graph from Google charts.

The data is structured like this:

```<code>KgPdzr3PgDaKVa73asd: {
    date: "29/03/201
    time: "15:21:07"
    value: 21.461541056632996
}
</code>```

Unfortunately the line graph won't load, and I can't figure out why. The json objects is loaded successfully, so I think it's got something to do with the drawing part of it.  Any help in the right direction will be most appreciated.

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="chart_div"></div></code>```

答:
Added (bold):     'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'

Made some minor changes as well. Cheers. Removed some errors by changing jquery version which is loaded.

```<code>      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
      <script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

      <script src="https://www.google.com/jsapi"></script>
      <script type="text/javascript">
          // Initialize Firebase
          var config = {
              apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
              authDomain: "internet-of-things-62d39.firebaseapp.com",
              databaseURL: "https://internet-of-things-62d39.firebaseio.com",
              projectId: "internet-of-things-62d39",
              storageBucket: "internet-of-things-62d39.appspot.com",
              messagingSenderId: "143567304866"
          };
          firebase.initializeApp(config);

          var database = firebase.database();

          firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
              temps = snapshot.val();
              console.log(temps);

              google.charts.load('current', {
                  'packages': ['corechart', 'line']
              });
              google.charts.setOnLoadCallback(drawChart(temps));
          });

          function parse(temp) {
              return (new Date(temp.replace(/-/g, '/'))).getTime()
          }

          function drawChart(temps) {
              var array = $.map(temps, function(value, index) {
                  return [value];
              });

              var data = new google.visualization.DataTable();
              data.addColumn('number', 'date');
              data.addColumn('number', 'time');
              data.addColumn('number', 'value');

              var sort = function(a, b) {
                  return parse(a.time) - parse(b.time)
              };
              var tempData = array.sort(sort);
              var output = [];

              for (var i = 0; i < tempData.length; i++) {
                  var item = tempData[i];
                  output.push([
                      //  parseFloat(parse(item.time)),
                      parseFloat(item.time),
                      parseFloat(item.date),
                      parseFloat(item.value)
                  ]);
              }
              console.log(output);
              data.addRows(output);

              var options = {
                  chart: {
                      title: 'title',
                      subtitle: 'subtitle'
                  },
                  width: 900,
                  height: 500
              };

              var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
              console.log("data + options: " + data, options)
              chart.draw(data, options);
          }

          google.charts.load('current', {
              'packages': ['corechart', 'line']
          });
          google.charts.setOnLoadCallback(drawChart);
      </script>
</code>```

Body:
I want to visualize some simple sensor readings stored in firebase in a basic line graph from Google charts.

The data is structured like this:

KgPdzr3PgDaKVa73asd: {
    date: "29/03/201
    time: "15:21:07"
    value: 21.461541056632996
}

Unfortunately the line graph won't load, and I can't figure out why. The json objects is loaded successfully, so I think it's got something to do with the drawing part of it.  Any help in the right direction will be most appreciated.

Body:
Added (bold):     'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'

Made some minor changes as well. Cheers. Removed some errors by changing jquery version which is loaded.

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
      <script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

      <script src="https://www.google.com/jsapi"></script>
      <script type="text/javascript">
          // Initialize Firebase
          var config = {
              apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
              authDomain: "internet-of-things-62d39.firebaseapp.com",
              databaseURL: "https://internet-of-things-62d39.firebaseio.com",
              projectId: "internet-of-things-62d39",
              storageBucket: "internet-of-things-62d39.appspot.com",
              messagingSenderId: "143567304866"
          };
          firebase.initializeApp(config);

          var database = firebase.database();

          firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
              temps = snapshot.val();
              console.log(temps);

              google.charts.load('current', {
                  'packages': ['corechart', 'line']
              });
              google.charts.setOnLoadCallback(drawChart(temps));
          });

          function parse(temp) {
              return (new Date(temp.replace(/-/g, '/'))).getTime()
          }

          function drawChart(temps) {
              var array = $.map(temps, function(value, index) {
                  return [value];
              });

              var data = new google.visualization.DataTable();
              data.addColumn('number', 'date');
              data.addColumn('number', 'time');
              data.addColumn('number', 'value');

              var sort = function(a, b) {
                  return parse(a.time) - parse(b.time)
              };
              var tempData = array.sort(sort);
              var output = [];

              for (var i = 0; i < tempData.length; i++) {
                  var item = tempData[i];
                  output.push([
                      //  parseFloat(parse(item.time)),
                      parseFloat(item.time),
                      parseFloat(item.date),
                      parseFloat(item.value)
                  ]);
              }
              console.log(output);
              data.addRows(output);

              var options = {
                  chart: {
                      title: 'title',
                      subtitle: 'subtitle'
                  },
                  width: 900,
                  height: 500
              };

              var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
              console.log("data + options: " + data, options)
              chart.draw(data, options);
          }

          google.charts.load('current', {
              'packages': ['corechart', 'line']
          });
          google.charts.setOnLoadCallback(drawChart);
      </script>


问:
Use Enum for checking condition
I am working on an application in which there are some fragment classes, which can be open by two ways in the application. The first way is Main Flow , the second way is through the Navigation Drawer.

So when the fragment is called from the Navigation Drawer than it will perform some task, and if it's call from the Main Flow than it will perform another task.

How can I check the context? Is there possibility through the use of Enum class.

Note:

I don't want to send the hardcoded value through the Intent.

答:
Firstly, you should avoid using enums in Android environment. Prefer to use @IntDef, @StringDef. The main reasoning behind this is the waste of resources. Enums take much more memory.

As Colt McAnlis shows in this perfmatters episode enums take 13x more space on rather trivial example.

Secondly, what you want to achieve may be done via Intents or Bundles, passing a boolean value from one component to another.

Title: Use Enum for checking condition


问:
Go lang how to check if float value is actually int
```<code>func isFloatInt(floatValue float64) bool{
//What's the implementation here?

}
</code>```

Test cases:

input: 1.5 output: false;

input: 1 output: true;

input:1.0 output: true;

答:
You could achieve it by doing a modulus</p>

```<code>func isFloatInt(floatValue float64) bool {
    return math.Mod(floatValue, 1.0) == 0
}
</code>```

Body:
func isFloatInt(floatValue float64) bool{
//What's the implementation here?

}

Test cases:

input: 1.5 output: false;

input: 1 output: true;

input:1.0 output: true;

Body:
You could achieve it by doing a modulus

func isFloatInt(floatValue float64) bool {
    return math.Mod(floatValue, 1.0) == 0
}


问:
condition to button for members and visitors
how can i add a condition to a button ? for visitors it will be LOGIN for logged in it will be changed to LOGOUT

another button will appear if member log in and disappear if he logged out

its a wordpress website and iam newbie in coding so please clarify where to put the code exactly

iam using button plugin for this button and i will put these buttons in the header area (above the navigation menu)
enter image description here

答:
As you tagged wordpress,so you can do it like below:-

```<code><?php if(is_user_logged_in()){?>
// your logout and other button code
<?php }else{?>
// your login button code
<?php } ?>
</code>```

Body:
As you tagged wordpress,so you can do it like below:-

<?php if(is_user_logged_in()){?>
// your logout and other button code
<?php }else{?>
// your login button code
<?php } ?>


问:
Are reset password links a bad idea?
We have a password reset web application. The application sends out an confirmation code to an alternative e-mail. My manager believes it is not a good idea to include a link to the page were you have to enter the code.

I see his argument. However, the helpdesk has been overwhelmed with users who are confused about the process. I'm assuming this is because many our users browse using only one tab/window and navigate out of our web application to check their e-mail for the confirmation code.

My question: How should we approach this issue? I would like to alleviate helpdesk and, in turn, make the process pain free for our users. Any suggestions?

Clarification

He believes that we are doing the user a disservice by training them to click links from a sender that cannot be verified (in this case, it's an automatic message with a "no-reply" address). This, would in turn, make users more susceptible to phishing attempts which we've had a lot of issues with in our organization.

答:
The only thing on the top of mind would be the option to have a unique identifier in the e-mail's subject an have the customers reply to that mail.

Then an automated script checks 'password-forgotten@mycompany.de' for emails with the subject 'Re: Forgot your password? [UNIQUEID]'. The script would then mail them their new password.

Since most users won't modify the subject when hitting "Reply To" and won't do a "Compose new mail" and enter the recipient address manually, chances are big, incoming mails to "password-forgotten" will have that UNIQUEID in the subject.

Plus helpdesk would only have help those that actually modify the email's "Subject". ;-)

There are security considerations, though. Maybe your manager might argue, that anyone might send a forged "Forgor your password" mail and set the "Reply-To" header to the attacker's address. The processing script has to intercept these attempts of forgery...

Title: Are reset password links a bad idea?


Title: Equivalent of two table() functions in dplyr

Body:
With data.table we can use dcast

library(data.table)
dcast(setDT(df), date~plan_type, length)
#         date PPU subscriber
#1: 2015-06-17   1          0
#2: 2015-07-03   1          0
#3: 2016-09-06   0          1
#4: 2016-10-07   0          1
#5: 2017-01-19   1          1


问:
Ajax request image
I want to make an AJAX request which contains a picture. Only the image is in a form, and need to be just the image.

```<code>var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);

var data = {
  id: id,
  title:title,
  photo:formdata
};

$.ajax({
  type: 'POST',
  enctype: 'multipart/form-data',
  url: '/my-url',
  data: JSON.stringify(data),
  processData: false,
  cache: false,
  contentType: false,
  success: function(response){
    console.log(response);
  },
  error: function(data){
    console.log("error");
    console.log(data);
  }
})
</code>```

I'm getting the id and title with .val(); and I want to keep this.., it's working fine for id and title, but I have no idea how to make work to send image to database.

答:
Your issue is because you're trying to append binary FormData to an object which is then serialised.

Instead you need to add the additional data to the FormData object so that it all can be encoded in the same way. Try this:

```<code>var form = $('form')[0];
var formData = new FormData(form);

formData.append('title', title);
formData.append('id', id);

$.ajax({
  type: 'POST',
  enctype: 'multipart/form-data',
  url: '/my-url',
  data: formData,
  processData: false,
  cache: false,
  contentType: false,
  success: function(response) {
    console.log(response);
  },
  error: function(data){
    console.log("error");
    console.log(data);
  }
})
</code>```

Note that if the id and title values are retrieved from input elements within the form, then you don't even need the append() lines, as they will automatically be included in the FormData as you provided the form to the constructor.

Also make sure you run this code under the submit event of the form element and call preventDefault. Don't put this under the click of the submit button.

Title: Ajax request image

Body:
I want to make an AJAX request which contains a picture. Only the image is in a form, and need to be just the image.

var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);

var data = {
  id: id,
  title:title,
  photo:formdata
};

$.ajax({
  type: 'POST',
  enctype: 'multipart/form-data',
  url: '/my-url',
  data: JSON.stringify(data),
  processData: false,
  cache: false,
  contentType: false,
  success: function(response){
    console.log(response);
  },
  error: function(data){
    console.log("error");
    console.log(data);
  }
})

I'm getting the id and title with .val(); and I want to keep this.., it's working fine for id and title, but I have no idea how to make work to send image to database.

Body:
Your issue is because you're trying to append binary FormData to an object which is then serialised.

Instead you need to add the additional data to the FormData object so that it all can be encoded in the same way. Try this:

var form = $('form')[0];
var formData = new FormData(form);

formData.append('title', title);
formData.append('id', id);

$.ajax({
  type: 'POST',
  enctype: 'multipart/form-data',
  url: '/my-url',
  data: formData,
  processData: false,
  cache: false,
  contentType: false,
  success: function(response) {
    console.log(response);
  },
  error: function(data){
    console.log("error");
    console.log(data);
  }
})

Note that if the id and title values are retrieved from input elements within the form, then you don't even need the append() lines, as they will automatically be included in the FormData as you provided the form to the constructor.

Also make sure you run this code under the submit event of the form element and call preventDefault. Don't put this under the click of the submit button.


问:
Dockerfile build using complex powershell script on windows container
I am trying to build a docker image with a dockerfile that runs powershell.  The embedded powershell script has already been tested outside of the dockerfile, but when running the dockerfile it has errors.

From docker file:

```<code>RUN powershell -NoProfile -Command " \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('http://localhost:8086', 'http://publichost.com:8086'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('database = "telegraf"', 'database = "qa"'); \
Set-Content c:\telegraf\telegraf.conf $lines \
"
</code>```

I got the following error:

```<code>At line:1 char:97
+ ... egraf.conf;     $pos = [array]::indexof($lines, $lines -match  global_ ...
+                                                                  ~
You must provide a value expression following the '-match' operator.
At line:1 char:97
+ ... egraf.conf;     $pos = [array]::indexof($lines, $lines -match global_ ...
+                                                                  ~
Missing ')' in method call.
At line:1 char:98
+ ...     $pos = [array]::indexof($lines, $lines -match global_tags);          $ ...
+ ~~~~~~~~~~~
Unexpected token 'global_tags' in expression or statement.
At line:1 char:109
+ ...    $pos = [array]::indexof($lines, $lines -match global_tags);         $l ...
+                                                                 ~
Unexpected token ')' in expression or statement.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
ception
+ FullyQualifiedErrorId : ExpectedValueExpression
</code>```

The purpose of the script is to add new content to specific line on the config file

any idea what wrong with the syntax?

答:
In order to resolve this issue I think you need to add additional double quotes  into the section of your command which replaces the database name.  To show an example I have pasted a Dockerfile below which produced the results I expected based on what I understand you are trying to achieve in the question.

```<code>FROM microsoft/windowsservercore

COPY telegraf.conf C:\\telegraf\\telegraf.conf

RUN powershell -NoProfile -Command " \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('http://localhost:8086', 'http://publichost.com:8086'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('database = """telegraf"""', 'database = """qa"""'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
"
</code>```

Obviously I expect your Dockerfile will look different, but if you take the example I have used above and add the additional double quotes around those that you have inside your string then you should find that it works as expected.

Any questions, let me know.

Body:
I am trying to build a docker image with a dockerfile that runs powershell.  The embedded powershell script has already been tested outside of the dockerfile, but when running the dockerfile it has errors.

From docker file:

RUN powershell -NoProfile -Command " \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('http://localhost:8086', 'http://publichost.com:8086'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('database = "telegraf"', 'database = "qa"'); \
Set-Content c:\telegraf\telegraf.conf $lines \
"

I got the following error:

At line:1 char:97
+ ... egraf.conf;     $pos = [array]::indexof($lines, $lines -match  global_ ...
+                                                                  ~
You must provide a value expression following the '-match' operator.
At line:1 char:97
+ ... egraf.conf;     $pos = [array]::indexof($lines, $lines -match global_ ...
+                                                                  ~
Missing ')' in method call.
At line:1 char:98
+ ...     $pos = [array]::indexof($lines, $lines -match global_tags);          $ ...
+ ~~~~~~~~~~~
Unexpected token 'global_tags' in expression or statement.
At line:1 char:109
+ ...    $pos = [array]::indexof($lines, $lines -match global_tags);         $l ...
+                                                                 ~
Unexpected token ')' in expression or statement.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
ception
+ FullyQualifiedErrorId : ExpectedValueExpression

The purpose of the script is to add new content to specific line on the config file

any idea what wrong with the syntax?

Body:
In order to resolve this issue I think you need to add additional double quotes  into the section of your command which replaces the database name.  To show an example I have pasted a Dockerfile below which produced the results I expected based on what I understand you are trying to achieve in the question.

FROM microsoft/windowsservercore

COPY telegraf.conf C:\\telegraf\\telegraf.conf

RUN powershell -NoProfile -Command " \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('http://localhost:8086', 'http://publichost.com:8086'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
$lines = (Get-Content c:\telegraf\telegraf.conf).replace('database = """telegraf"""', 'database = """qa"""'); \
Set-Content c:\telegraf\telegraf.conf $lines; \
"

Obviously I expect your Dockerfile will look different, but if you take the example I have used above and add the additional double quotes around those that you have inside your string then you should find that it works as expected.

Any questions, let me know.


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答:
I agree with @stillstanding on the issue of interchangeability within HTML. However, in PHP I use double quotes in instances where I need a variable within a string parsed. Consider this:

```<code><?php
    $id = 123;
    echo "Your id is $id<br />";
    echo 'Your id is $id';
?>
</code>```

This will output

Your id is 123

Your id is $id

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>

Body:
I agree with @stillstanding on the issue of interchangeability within HTML. However, in PHP I use double quotes in instances where I need a variable within a string parsed. Consider this:

<?php
    $id = 123;
    echo "Your id is $id<br />";
    echo 'Your id is $id';
?>

This will output

Your id is 123

Your id is $id


问:
sp_executesql with always true condition
i have been using dynamic queries in sql-server like:

```<code>declare @sql nvarchar (1000),@condition nvarchar(100)='';
set @sql=N'select * from tablename where (0=0)'+@condition+'';
exec(@sql)
</code>```

by this i was able to get my result whether the @condition has any value or not.
But i got to know that sp_executesql is better then exec as it promote query plan reuse.

So, i tried my query with `sp_executesql,

```<code>set @sql =N'select * from dbo.testclient where (0=0) @condition'
exec sp_executesql @sql,N'@condition nvarchar(100)',@condition
</code>```

but it failed with an error as

```<code>Incorrect syntax near '@condition'.
</code>```

My problem is how can i make the above query to work with sp_executesql where the parameter @condition can be a condition or blank (' ') and what am i doing wrong.

答:
Tested code,</p>

```<code>     DECLARE @Sql   nvarchar(MAX)='',
        @paramlist  nvarchar(4000),
 @id int=3
 set @paramlist = N' @id1 int'
set @Sql='select * from test where id=@id1'

exec sp_executesql @Sql,@paramlist,@id
select @Sql
</code>```

Body:
i have been using dynamic queries in sql-server like:

declare @sql nvarchar (1000),@condition nvarchar(100)='';
set @sql=N'select * from tablename where (0=0)'+@condition+'';
exec(@sql)

by this i was able to get my result whether the @condition has any value or not.
But i got to know that sp_executesql is better then exec as it promote query plan reuse.

So, i tried my query with `sp_executesql,

set @sql =N'select * from dbo.testclient where (0=0) @condition'
exec sp_executesql @sql,N'@condition nvarchar(100)',@condition

but it failed with an error as

Incorrect syntax near '@condition'.

My problem is how can i make the above query to work with sp_executesql where the parameter @condition can be a condition or blank (' ') and what am i doing wrong.

Body:
Tested code,

     DECLARE @Sql   nvarchar(MAX)='',
        @paramlist  nvarchar(4000),
 @id int=3
 set @paramlist = N' @id1 int'
set @Sql='select * from test where id=@id1'

exec sp_executesql @Sql,@paramlist,@id
select @Sql


问:
Move onto next item in array every time function is called JavaScript
I basically want to change the position of a character every time a function is called.

So this is where I'm calling my function,

```<code> timer = game.time.create(false);
 timer.add(2000, this.toggleCurrentCharacter, this);
 timer.start();
</code>```

And my function it calls looks like this,

```<code>toggleCurrentCharacter:function() {
      var characterArr = [characterA, characterB, characterC];
      var characterPosArr = [LEFT_CENTER, CENTER, RIGHT_CENTER];

      characterA.alignIn(columnLeft, Phaser.CENTER);
      characterB.alignTo(columnLeft, Phaser.RIGHT_CENTER);
      characterC.alignTo(columnLeft, Phaser.LEFT_CENTER);

      console.log("Testing");

      timer.add(2000, this.toggleCurrentCharacter, this);
}
</code>```

the timer.add is just making sure my function runs endlessly.

Each time the function runs I want to change the alignment of a sprite I've got, so the RIGHT_CENTER, CENTER, etc you see.

I figured I'd need an array to iterate over, but I'm unable to understand and figure out how each time I call the function, the Phaser.RIGHT_CENTER will iterate over so for example, the next time I call the function Phaser.RIGHT_CENTER now looks like Phaser.CENTER and so on.

Thanks

答:
You can write a function called rotate:

```<code>function rotate(array) {
  return array.splice(1).concat(array);
}
</code>```

or any number of other permutations:

```<code>function rotate(array) {
  return array.concat(array.shift());
}
</code>```

Body:
I basically want to change the position of a character every time a function is called.

So this is where I'm calling my function,

 timer = game.time.create(false);
 timer.add(2000, this.toggleCurrentCharacter, this);
 timer.start();

And my function it calls looks like this,

toggleCurrentCharacter:function() {
      var characterArr = [characterA, characterB, characterC];
      var characterPosArr = [LEFT_CENTER, CENTER, RIGHT_CENTER];

      characterA.alignIn(columnLeft, Phaser.CENTER);
      characterB.alignTo(columnLeft, Phaser.RIGHT_CENTER);
      characterC.alignTo(columnLeft, Phaser.LEFT_CENTER);

      console.log("Testing");

      timer.add(2000, this.toggleCurrentCharacter, this);
}

the timer.add is just making sure my function runs endlessly.

Each time the function runs I want to change the alignment of a sprite I've got, so the RIGHT_CENTER, CENTER, etc you see.

I figured I'd need an array to iterate over, but I'm unable to understand and figure out how each time I call the function, the Phaser.RIGHT_CENTER will iterate over so for example, the next time I call the function Phaser.RIGHT_CENTER now looks like Phaser.CENTER and so on.

Thanks

Body:
You can write a function called rotate:

function rotate(array) {
  return array.splice(1).concat(array);
}

or any number of other permutations:

function rotate(array) {
  return array.concat(array.shift());
}


问:
Spring's @JmsListener only receiving one message from Solace queue
I have just configured a listener using Spring's @JmsListener, yet when I use a single method parameter, I only receive one message from my queue.

```<code>@JmsListener(...)
public void onMessage(Message message)
</code>```

It doesn't behave like a traditional listener in this case - only one messaged is ever received! Not an influx of single messages one at a time as I would expect.

However, if I change the method definition to become

```<code>@JmsListener(...)
public void onMessage(List<Message> messages)
</code>```

I receive all of them as a list. This has never happened before, and the only unknown in this instance is how the Solace queue is configured. Are there batch settings on the queue I may not be aware of?

答:
Turns out that the messages were actually being sent as a list!

As in:

```<code>jmsTemplate.convertAndSend(listOfMessages);
</code>```

It seems Spring only allows the first in this list to be accessed if you define your listener as:

```<code>public void onMessage(Message message){}
</code>```

Body:
I have just configured a listener using Spring's @JmsListener, yet when I use a single method parameter, I only receive one message from my queue.

@JmsListener(...)
public void onMessage(Message message)

It doesn't behave like a traditional listener in this case - only one messaged is ever received! Not an influx of single messages one at a time as I would expect.

However, if I change the method definition to become

@JmsListener(...)
public void onMessage(List<Message> messages)

I receive all of them as a list. This has never happened before, and the only unknown in this instance is how the Solace queue is configured. Are there batch settings on the queue I may not be aware of?

Body:
Turns out that the messages were actually being sent as a list!

As in:

jmsTemplate.convertAndSend(listOfMessages);

It seems Spring only allows the first in this list to be accessed if you define your listener as:

public void onMessage(Message message){}


问:
Changes in package.json for Angular 2 to 4 migration
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}
</code>```

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

```<code>{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}
</code>```

答: There is an online app that guides you in the (easy) process of upgrading 2 to 4: https://angular-update-guide.firebaseapp.com/</p>

Body:
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}


问:
Java Input from formatted file
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

```<code>The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
</code>```

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

答: Read the file line by line, use the [^,:] regular expression to match data in each line (sequential find will bring title, author, and borrower, state, if any).

Title: Java Input from formatted file

Body:
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.


问:
Best Angular javascript Grid
I need to implement a Microsoft Solution with Angular Js.
Solution have one Microsoft .Net Web Api for Crud operations, and MVC5 Project with angular js. I need an angular js grid where show data from web api json. I need i grid with paging and search. No inline editing functions.

I see ng-grid. Is it the best solution?

Thanks

答: ng-grid is good. Lots of functionality it has. you can also use smart table. Less functionality than ng-grid but too easy to use. the functionality you told I think all will be easily covered. Its a suggestion but ng-grid is fantastic with a lot of functionalities.</p>

Title: Best Angular javascript Grid


问:
LINQ - Group by calculated field
Say I have some class like this:

```<code>public class MyClass
{
    public DateTime Date { get; set; }
    public string Code { get; set; }
}
</code>```

And some values like:

```<code>| Date          | Code  |
|------------   |------ |
| 03/04/2017    | 1234  |
| 31/03/2017    | 1234  |
| 29/03/2017    | 1234  |
| 29/03/2017    | 4321  |
| 25/03/2017    | 4321  |
| ...           | ...   |
</code>```

I want to group these by the Code field AND also group by the Date however I want the Date to be grouped by a range. The calculation on this will find the date at the start of the week (Monday of that week) and also the end of the week (Friday of that week) and then give me some results like:

```<code>| 03/04/2017    | 1234  | < week beginning 03/04 and code=1234

| 31/03/2017    | 1234  | < week beginning 27/03 and code=1234
| 29/03/2017    | 1234  |

| 29/03/2017    | 4321  | < week beginning 27/03 and code=4321

| 25/03/2017    | 4321  | < week beginning 20/03 and code=4321
</code>```

I've tried doing a range but I think what I'm doing is pretty useless (StartOfWeek is an extension method from here):

```<code>data.Where(d => d.Date >= d.Date.StartOfWeek(DayOfWeek.Monday) && d.Date <= d.Date.StartOfWeek(DayOfWeek.Monday).AddDays(6));
</code>```

Note: I'm using Entity Framework for my actual project but when I'm doing this I am fetching all the data from the MyClass table and I want to do all the above to filter and group the data appropriately.

答:
The code below uses Sunday as the 1st day of the week.  To get the week you need to divide the Day of the Year by 7.  If the 1st day of the year is Monday you need to add 1 to Day of the Year So that the days of the week are Sun = 0, Monday = 1, .... Since Jan 1 is day 1 (not 0) so the divide method works correctly.</p>

```<code>            DataTable dt = new DataTable();
            dt.Columns.Add("Date",typeof(DateTime));
            dt.Columns.Add("Code",typeof(int));

            dt.Rows.Add(new object[] { DateTime.Parse("04/03/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/31/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/29/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/29/2017"), 4321});
            dt.Rows.Add(new object[] { DateTime.Parse("03/25/2017"), 4321});

            var groups = dt.AsEnumerable().GroupBy(x => (int)(x.Field<DateTime>("Date").DayOfYear + (int)new DateTime(x.Field<DateTime>("Date").Year, 1, 1).DayOfWeek)/7).ToList();
</code>```

Title: LINQ - Group by calculated field

Body:
Say I have some class like this:

public class MyClass
{
    public DateTime Date { get; set; }
    public string Code { get; set; }
}

And some values like:

| Date          | Code  |
|------------   |------ |
| 03/04/2017    | 1234  |
| 31/03/2017    | 1234  |
| 29/03/2017    | 1234  |
| 29/03/2017    | 4321  |
| 25/03/2017    | 4321  |
| ...           | ...   |

I want to group these by the Code field AND also group by the Date however I want the Date to be grouped by a range. The calculation on this will find the date at the start of the week (Monday of that week) and also the end of the week (Friday of that week) and then give me some results like:

| 03/04/2017    | 1234  | < week beginning 03/04 and code=1234

| 31/03/2017    | 1234  | < week beginning 27/03 and code=1234
| 29/03/2017    | 1234  |

| 29/03/2017    | 4321  | < week beginning 27/03 and code=4321

| 25/03/2017    | 4321  | < week beginning 20/03 and code=4321

I've tried doing a range but I think what I'm doing is pretty useless (StartOfWeek is an extension method from here):

data.Where(d => d.Date >= d.Date.StartOfWeek(DayOfWeek.Monday) && d.Date <= d.Date.StartOfWeek(DayOfWeek.Monday).AddDays(6));

Note: I'm using Entity Framework for my actual project but when I'm doing this I am fetching all the data from the MyClass table and I want to do all the above to filter and group the data appropriately.

Body:
The code below uses Sunday as the 1st day of the week.  To get the week you need to divide the Day of the Year by 7.  If the 1st day of the year is Monday you need to add 1 to Day of the Year So that the days of the week are Sun = 0, Monday = 1, .... Since Jan 1 is day 1 (not 0) so the divide method works correctly.

            DataTable dt = new DataTable();
            dt.Columns.Add("Date",typeof(DateTime));
            dt.Columns.Add("Code",typeof(int));

            dt.Rows.Add(new object[] { DateTime.Parse("04/03/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/31/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/29/2017"), 1234});
            dt.Rows.Add(new object[] { DateTime.Parse("03/29/2017"), 4321});
            dt.Rows.Add(new object[] { DateTime.Parse("03/25/2017"), 4321});

            var groups = dt.AsEnumerable().GroupBy(x => (int)(x.Field<DateTime>("Date").DayOfYear + (int)new DateTime(x.Field<DateTime>("Date").Year, 1, 1).DayOfWeek)/7).ToList();


问:
How to selectively read xml file
How to selectively read the xml below so that when confronted with tags  with similar names, the xml reader would skip the first tag.

```<code><paraphrase_candidates source_description="id:9249">
    <annotation author="87" is_paraphrase="true" source_description="id:18689" >
        <phenomenon type="lex_same_polarity" projection="local"                                        source_description="id:5528">
            <snippet id="16488" >
                <scope offset="125" length="4"/>
            </snippet>
            <snippet id="16489" >
                <scope offset="71" length="11"/>
            </snippet>
        </phenomenon>
        <phenomenon type="syn_diathesis" source_description="id:5536">
            <snippet id="16488" >
                <scope offset="32" length="92"/>
            </snippet>
                <scope offset="0" length="70"/>
        </phenomenon>
    </annotation>
</paraphrase_candidates>
</code>```

Specifically,  I would like to skip the first phenomenon tag and retrieve the scope attribute of the second phenomenon tag.

```<code>My attempts
for x in root.findall('scope'):
    print x.attrib[0]
</code>```

Output: empty

expected output:{offset="32" length="92"} and {offset="0" length="70}

答:
root.findall('scope') returned empty because scope aren't direct child of root in your XML. Using .//scope instead (see the docs) will get you all scope elements in the XML.

To get only scope elements from the 2nd phenomenon, you can use position index predicate (note that XPath position index start from 1, not 0) :

```<code>root.findall('.//phenomenon[2]//scope')
</code>```

Test codes :

```<code>>>> raw = '''<paraphrase_candidates source_description="id:9249">
...     <annotation author="87" is_paraphrase="true" source_description="id:18689" >
...         <phenomenon type="lex_same_polarity" projection="local"
              source_description="id:5528">
...             <snippet id="16488" >
...                 <scope offset="125" length="4"/>
...             </snippet>
...             <snippet id="16489" >
...                 <scope offset="71" length="11"/>
...             </snippet>
...         </phenomenon>
...         <phenomenon type="syn_diathesis" source_description="id:5536">
...             <snippet id="16488" >
...                 <scope offset="32" length="92"/>
...             </snippet>
...                 <scope offset="0" length="70"/>
...         </phenomenon>
...     </annotation>
... </paraphrase_candidates>'''
>>> from xml.etree import ElementTree as et
>>> root = et.fromstring(raw)
>>> for x in root.findall('.//phenomenon[2]//scope'):
...     print x.attrib
...
{'length': '92', 'offset': '32'}
{'length': '70', 'offset': '0'}
</code>```

Title: How to selectively read xml file

Body:
How to selectively read the xml below so that when confronted with tags  with similar names, the xml reader would skip the first tag.

<paraphrase_candidates source_description="id:9249">
    <annotation author="87" is_paraphrase="true" source_description="id:18689" >
        <phenomenon type="lex_same_polarity" projection="local"                                        source_description="id:5528">
            <snippet id="16488" >
                <scope offset="125" length="4"/>
            </snippet>
            <snippet id="16489" >
                <scope offset="71" length="11"/>
            </snippet>
        </phenomenon>
        <phenomenon type="syn_diathesis" source_description="id:5536">
            <snippet id="16488" >
                <scope offset="32" length="92"/>
            </snippet>
                <scope offset="0" length="70"/>
        </phenomenon>
    </annotation>
</paraphrase_candidates>

Specifically,  I would like to skip the first phenomenon tag and retrieve the scope attribute of the second phenomenon tag.

My attempts
for x in root.findall('scope'):
    print x.attrib[0]

Output: empty

expected output:{offset="32" length="92"} and {offset="0" length="70}

Body:
root.findall('scope') returned empty because scope aren't direct child of root in your XML. Using .//scope instead (see the docs) will get you all scope elements in the XML.

To get only scope elements from the 2nd phenomenon, you can use position index predicate (note that XPath position index start from 1, not 0) :

root.findall('.//phenomenon[2]//scope')

Test codes :

>>> raw = '''<paraphrase_candidates source_description="id:9249">
...     <annotation author="87" is_paraphrase="true" source_description="id:18689" >
...         <phenomenon type="lex_same_polarity" projection="local"
              source_description="id:5528">
...             <snippet id="16488" >
...                 <scope offset="125" length="4"/>
...             </snippet>
...             <snippet id="16489" >
...                 <scope offset="71" length="11"/>
...             </snippet>
...         </phenomenon>
...         <phenomenon type="syn_diathesis" source_description="id:5536">
...             <snippet id="16488" >
...                 <scope offset="32" length="92"/>
...             </snippet>
...                 <scope offset="0" length="70"/>
...         </phenomenon>
...     </annotation>
... </paraphrase_candidates>'''
>>> from xml.etree import ElementTree as et
>>> root = et.fromstring(raw)
>>> for x in root.findall('.//phenomenon[2]//scope'):
...     print x.attrib
...
{'length': '92', 'offset': '32'}
{'length': '70', 'offset': '0'}


答:
I just checked on the playground, this does the right thing with NaN as well.</p>

```<code>func isIntegral(val float64) bool {
    return val == float64(int(val))
}
</code>```

Title: Go lang how to check if float value is actually int

Body:
func isFloatInt(floatValue float64) bool{
//What's the implementation here?

}

Test cases:

input: 1.5 output: false;

input: 1 output: true;

input:1.0 output: true;

Body:
I just checked on the playground, this does the right thing with NaN as well.

func isIntegral(val float64) bool {
    return val == float64(int(val))
}


问:
Dynamic web page scraping using python
I am running below code, but i am getting an empty list. Can you please help me in find out the issue.

execution: xvfb-run python dynamic_scrapy.py

```<code>import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs

class Client(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self.on_page_load)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
    def on_page_load(self):
        self.app.quit()

url = "https://pythonprogramming.net/parsememcparseface/"
client_response = Client(url)
source = client_response.mainFrame().toHtml()
soup = bs.BeautifulSoup(source, 'lxml')
print(soup)
js_test = soup.find_all('p', class_='jstest')
print(js_test)
</code>```

答:
You need to convert the QString into string to pass it into BeautifulSoup. You can do something like this :

```<code>import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs

class Client(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self.on_page_load)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
    def on_page_load(self):
        self.app.quit()

url = "https://pythonprogramming.net/parsememcparseface/"
client_response = Client(url)

source = client_response.mainFrame().toHtml()
source_utf = unicode(source.toUtf8(), encoding="UTF-8") # Added
soup = bs.BeautifulSoup(source_utf, 'lxml')
js_test = soup.find_all('p', class_='jstest')
print(js_test)
</code>```

This will result in :

```<code>[<p class="jstest" id="yesnojs">Look at you shinin!</p>]
</code>```

Title: Dynamic web page scraping using python

Body:
I am running below code, but i am getting an empty list. Can you please help me in find out the issue.

execution: xvfb-run python dynamic_scrapy.py

import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs

class Client(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self.on_page_load)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
    def on_page_load(self):
        self.app.quit()

url = "https://pythonprogramming.net/parsememcparseface/"
client_response = Client(url)
source = client_response.mainFrame().toHtml()
soup = bs.BeautifulSoup(source, 'lxml')
print(soup)
js_test = soup.find_all('p', class_='jstest')
print(js_test)

Body:
You need to convert the QString into string to pass it into BeautifulSoup. You can do something like this :

import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs

class Client(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self.on_page_load)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
    def on_page_load(self):
        self.app.quit()

url = "https://pythonprogramming.net/parsememcparseface/"
client_response = Client(url)

source = client_response.mainFrame().toHtml()
source_utf = unicode(source.toUtf8(), encoding="UTF-8") # Added
soup = bs.BeautifulSoup(source_utf, 'lxml')
js_test = soup.find_all('p', class_='jstest')
print(js_test)

This will result in :

[<p class="jstest" id="yesnojs">Look at you shinin!</p>]


问:
Should I use real or sample data for unit tests?
I'm writing a parser for the output of a legacy application, and since there are no specs on the file syntax I've got as many samples of these files as I could.

Now I'm writing the unit tests before implementing the parser (because there is no other sane way to do this) but I'm not sure whether I should:

use the real files produced by the application, reading from them and comparing the output with the output that I would store in json format in another file.

or create a sample string with the tokens and possibilities I want to test and a dict (this is python) with the expected output.

I'm inclined to use the second alternative because I would test only what I need to, without all the "real-world" data included on the actual files, but I'm afraid I could forget to test for one possibility or another.

What do you think?

答:
Production data can be a good starting point (assuming it's not sensitive info), since there's a good chance you can't think of all the possible permutations yourself. However, once you get a good working set of data, save it somewhere static, like a file. Then have the tests get it from there instead of dynamically from the production environment.  That way you can run the tests with a known set of inputs every time.

The alternative, getting production data on the fly for test inputs, is fraught with problems. Changes in the data could cause a test to pass one time, but fail the next because the inputs changed.


问:
TextBox_TextChanged Event not firing in c#
The DOB_TextChanged event not firing.My code is,

Aspx code

```<code><asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>
</code>```

code behind,

```<code>protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}
</code>```

am i did anything wrong??

答:
You can use LinkButton and OnRowCommand instead:

Aspx

```<code><EditItemTemplate>
    <asp:LinkButton ID="test" CommandName="YourCommandName" runat="server">Test</asp:LinkButton>

</EditItemTemplate>
</code>```

CodeBehind:

```<code>protected void Item_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "YourCommandName")
    {
         //to do
    }
}
</code>```

Body:
The DOB_TextChanged event not firing.My code is,

Aspx code

<asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>

code behind,

protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}

am i did anything wrong??

Body:
You can use LinkButton and OnRowCommand instead:

Aspx

<EditItemTemplate>
    <asp:LinkButton ID="test" CommandName="YourCommandName" runat="server">Test</asp:LinkButton>

</EditItemTemplate>

CodeBehind:

protected void Item_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "YourCommandName")
    {
         //to do
    }
}


问:
Implements vs extends: When to use? What's the difference?
Please explain in an easy to understand language or a link to some article.</p>

答:
We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks.
But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

```<code>class AnimalClass {

public void doEat() {

    System.out.println("Animal Eating...");
}

public void sleep() {

    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {

    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();

    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {

    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub

}

@Override
public void herbiEating() {

    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub

}

}
</code>```

Defined Interfaces :

```<code>public interface AnimalInterface {

public void eating();

}

interface Herbi {

public void herbiEating();

}
</code>```

Body:
We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks.
But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {

    System.out.println("Animal Eating...");
}

public void sleep() {

    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {

    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();

    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {

    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub

}

@Override
public void herbiEating() {

    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub

}

}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}

interface Herbi {

public void herbiEating();

}