问:
Oddity: index out of bounds, in creation (NOT assignment)
So - I still can't figure out why this line:

```<code>List<string> strTemp = new List<string>();
</code>```

Would throw this error:

Index was outside the bounds of the array.

Some context: Recursive function, called (initially) from function launched in separate thread from Web Service (IIS).

Also - lest too many jump in with "perhaps you are looking at the wrong line..." - no.   easily confirmed.  Move line, moves error, with each deployment.

Oh - and for the record - not always, it's an occasional (they're so much fun).
From what I can see in the event log, no issues  "around" the time of the flagging that would indicate any complicating factor.

Edit: some details for the comments below.
public class for service: SuperCloud

public class for queuer: PHQ

public function (called from service): void OnStop()

public function causing error: (snip from decl to line in question)

```<code>    public string CoalesceStrings(List<string> strIn, string[] strDelim = null)
    {
        string strReturn;
        List<string> strTempReturn;
        List<string> strTemp = new List<string>(); //<== error here!
        string[][] strTemp2;
        int iCount, iCap = int.MaxValue;

        if (strDelim == null)
            strDelim = new string[] { "." };

        iCount = strIn.Count;
        strTemp2 = new string[iCount][];

        for (int i = 0; i < iCount; i++)
        {
            strTemp2[i] = strIn[i].Split(strDelim, StringSplitOptions.None);
            if (strTemp2[i].Length < iCap)
                iCap = strTemp2[i].Length;
        }

        strTempReturn = new List<string>();
        if (strDelim[0] == ".")
            --iCap;

        for (int i = 0; i < iCap; i++)
        {
            bool bMatch = true;
            strTemp.Clear();
            strTemp.Add( strTemp2[0][i] );

            for (int j = 1; j < iCount; j++)
            {
                strTemp.Add(strTemp2[j][i]);
                if (bMatch && (strTemp2[j][i] != strTemp2[0][i]))
                    bMatch = false;
            }

            if (bMatch)
                strTempReturn.Add(strTemp2[0][i]);
            else if (strDelim[0] == "." )
                strTempReturn.Add( CoalesceStrings( strTemp, new string [] {"_"} ));
        }

        if (strDelim[0] == ".")
            strTempReturn.Add(strTemp2[0][strTemp2[0].Length - 1]);

        if (strTempReturn.Count == 0)
            strReturn = "";
        else
        {
            strReturn = strTempReturn[0];

            for (int i = 1; i < strTempReturn.Count; i++)
                strReturn = string.Concat(strReturn, strDelim[0], strTempReturn[i]);
        }

        return strReturn;
    }
</code>```

edited: added full function for mjwillis
call: CoalesceStrings(strFileName);

basically: the function will take a set of files that originated from a single file, that were split, according to an unknown algorithm, and "unsplit" it, to get the original file name.  The logic itself works (the times it doesn't throw the error).

example:
input: { "foo.bar.1.1.prelim", "foo.bar.1.1.final", "foo.bar.1.2.prelim",...,"foo.bar.4.5.final" }
output: "foo.bar"

答:
Change:

```<code>    if (strDelim == null)
        strDelim = new string[] { "." };
</code>```

to:

```<code>    if (strDelim == null || !strDelim.Any())
        strDelim = new string[] { "." };

    if (strIn == null)
        strIn = new List<string>();
</code>```

Does that help?

Honestly, it would help greatly if the variable names weren't all derivations of temp - it makes it very hard to work out what the code is even trying to do...

Body:
So - I still can't figure out why this line:

List<string> strTemp = new List<string>();

Would throw this error:

Index was outside the bounds of the array.

Some context: Recursive function, called (initially) from function launched in separate thread from Web Service (IIS).

Also - lest too many jump in with "perhaps you are looking at the wrong line..." - no.   easily confirmed.  Move line, moves error, with each deployment.

Oh - and for the record - not always, it's an occasional (they're so much fun).
From what I can see in the event log, no issues  "around" the time of the flagging that would indicate any complicating factor.

Edit: some details for the comments below.
public class for service: SuperCloud

public class for queuer: PHQ

public function (called from service): void OnStop()

public function causing error: (snip from decl to line in question)

    public string CoalesceStrings(List<string> strIn, string[] strDelim = null)
    {
        string strReturn;
        List<string> strTempReturn;
        List<string> strTemp = new List<string>(); //<== error here!
        string[][] strTemp2;
        int iCount, iCap = int.MaxValue;

        if (strDelim == null)
            strDelim = new string[] { "." };

        iCount = strIn.Count;
        strTemp2 = new string[iCount][];

        for (int i = 0; i < iCount; i++)
        {
            strTemp2[i] = strIn[i].Split(strDelim, StringSplitOptions.None);
            if (strTemp2[i].Length < iCap)
                iCap = strTemp2[i].Length;
        }

        strTempReturn = new List<string>();
        if (strDelim[0] == ".")
            --iCap;

        for (int i = 0; i < iCap; i++)
        {
            bool bMatch = true;
            strTemp.Clear();
            strTemp.Add( strTemp2[0][i] );

            for (int j = 1; j < iCount; j++)
            {
                strTemp.Add(strTemp2[j][i]);
                if (bMatch && (strTemp2[j][i] != strTemp2[0][i]))
                    bMatch = false;
            }

            if (bMatch)
                strTempReturn.Add(strTemp2[0][i]);
            else if (strDelim[0] == "." )
                strTempReturn.Add( CoalesceStrings( strTemp, new string [] {"_"} ));
        }

        if (strDelim[0] == ".")
            strTempReturn.Add(strTemp2[0][strTemp2[0].Length - 1]);

        if (strTempReturn.Count == 0)
            strReturn = "";
        else
        {
            strReturn = strTempReturn[0];

            for (int i = 1; i < strTempReturn.Count; i++)
                strReturn = string.Concat(strReturn, strDelim[0], strTempReturn[i]);
        }

        return strReturn;
    }

edited: added full function for mjwillis
call: CoalesceStrings(strFileName);

basically: the function will take a set of files that originated from a single file, that were split, according to an unknown algorithm, and "unsplit" it, to get the original file name.  The logic itself works (the times it doesn't throw the error).

example:
input: { "foo.bar.1.1.prelim", "foo.bar.1.1.final", "foo.bar.1.2.prelim",...,"foo.bar.4.5.final" }
output: "foo.bar"

Body:
Change:

    if (strDelim == null)
        strDelim = new string[] { "." };

to:

    if (strDelim == null || !strDelim.Any())
        strDelim = new string[] { "." };

    if (strIn == null)
        strIn = new List<string>();

Does that help?

Honestly, it would help greatly if the variable names weren't all derivations of temp - it makes it very hard to work out what the code is even trying to do...


来源: stackexchange

问:
How to find if button is in active state in ionic app
In my ionic app, I have a screen which has 2 buttons. On pressing each of those buttons, I call a function which does some intensive network task. Everything is working well.

Normally when I press one of those button, it calls the function. But if I press that button again, it again calls that function and does same work. I dont want it do call function again if I had pressed before. Only if I press another button and then press this button again, it should call the function.

So, can I get to know the active state of my button before calling the function?

I am new to Ionic, so would appreciate any help on this.

Button code :

```<code><div class="button-bar button-bar-full bar-light"
             ng-if="activityLog.enabledChecked && !activityLog.disabledToggle">
            <a class="button" ng-class="{'button-active': activityLog.isUnblockedFiltered}"
               ng-click="switchFilter(true)">{{ 'main.activity-log-blocked-report' | i18n }}</a>
            <a class="button" ng-class="{'button-active': !activityLog.isUnblockedFiltered}"
               ng-click="switchFilter(false)">{{ 'main.activity-log-full-report' | i18n }}</a>
        </div>
</code>```

PS: I can apply some flags and can make this work but want to know if I can get to know the state of button by some api.

Thanks

答:
In your view bind the ng-disabled to a property in the controller "disableButton" as shown below and while clicking the button make it true. Then the button will get disabled while doing api call and in completion you can make it false to enable the button again.</p>

```<code><a class="button" ng-disabled="disableButton" ng-class="{'button-active': activityLog.isUnblockedFiltered}"
           ng-click="switchFilter(true)">{{ 'main.activity-log-blocked-report' | i18n }}</a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my ionic app, I have a screen which has 2 buttons. On pressing each of those buttons, I call a function which does some intensive network task. Everything is working well.

Normally when I press one of those button, it calls the function. But if I press that button again, it again calls that function and does same work. I dont want it do call function again if I had pressed before. Only if I press another button and then press this button again, it should call the function.

So, can I get to know the active state of my button before calling the function?

I am new to Ionic, so would appreciate any help on this.

Button code :

            {{ 'main.activity-log-blocked-report' | i18n }}
            {{ 'main.activity-log-full-report' | i18n }}

PS: I can apply some flags and can make this work but want to know if I can get to know the state of button by some api.

Thanks

Body:
In your view bind the ng-disabled to a property in the controller "disableButton" as shown below and while clicking the button make it true. Then the button will get disabled while doing api call and in completion you can make it false to enable the button again.

<a class="button" ng-disabled="disableButton" ng-class="{'button-active': activityLog.isUnblockedFiltered}"
           ng-click="switchFilter(true)">{{ 'main.activity-log-blocked-report' | i18n }}</a>


问:
Substring with emoj in swift
I have a string "hi @ ". if I check length of this string it comes 6. If I write string.characters[5] getting array index out of bound exception.Why ?? How to extract  .?

to check the length I am using string.utf16.count.

答:
You get the error due to the fact that emojis are represented as Unicode characters, which don't necessarily have a length of 1, so you should always use indexes obtained from .index(of:) function to access characters of a string that contains emojis.

Have a look at this playground snippet, which shows you how to get emojis out of Strings safely.

```<code>let s = "hi @ , bye ☀ asd"
s.characters.count
s.characters.index(of: "")
if let emojiIndex = s.characters.index(of: "") {
    s[emojiIndex]
}
s.characters.index(of: "☀")
if let emojiIndex = s.characters.index(of: "☀") {
    s[emojiIndex]
}
</code>```

Title: Substring with emoj in swift

Body:
You get the error due to the fact that emojis are represented as Unicode characters, which don't necessarily have a length of 1, so you should always use indexes obtained from .index(of:) function to access characters of a string that contains emojis.

Have a look at this playground snippet, which shows you how to get emojis out of Strings safely.

let s = "hi @ , bye ☀ asd"
s.characters.count
s.characters.index(of: "")
if let emojiIndex = s.characters.index(of: "") {
    s[emojiIndex]
}
s.characters.index(of: "☀")
if let emojiIndex = s.characters.index(of: "☀") {
    s[emojiIndex]
}


问:
Is this failing radio button feature test a Capybara syntax issue?
I have a form with a radio button for a boolean attr prev_cover, displays Yes or No in browser with param values of true or false and saved in db as true or false as data type boolean. I am trying to:

a) model test presence of a selection of the radio buttons

b) feature test the creation of a whole quote record.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('No') } the create_quote_spec test fails, model quote.rb test passes.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('Yes') } the create_quote_spec test passes, model quote.rb test passes.

In actual manual browser testing the db record is created when either Yes or No is selected.

When I remove presence validation of prev_cover from quote.rb the create_quote_spec passes with with prev_cover Yes or No selected, but of course the model quote_spec.rb test fails.

I cannot see where the problem is here, is it something to do with the capybara within(".quote_prev_cover") { choose('No') } syntax perhaps? (it finds that css element just fine)

Here's form element of new.html.erb

```<code><div class='container'>
    <div class='row'>
        <div class='col-md-6'>
            <%= simple_form_for @quote do |f| %>
                <%= f.input :prev_cover, as: :radio_buttons, label: "Previous cover" %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>
        </div>
    </div>
</div>
</code>```

Here's quote.rb validation;

```<code>validates :prev_cover, inclusion: { in: [true, false] }
</code>```

Here's prev_cover element of the called NewQuoteFrom.new being created by Capybara;

```<code>within(".quote_prev_cover") { choose('No') }
</code>```

Here's test that fails if chooses prev_cover 'No' and passes if chooses 'Yes', create_quote_spec.rb

```<code>feature 'creating quote request' do
let(:user) { FactoryGirl.create(:user) }
let(:new_quote_form) { NewQuoteForm.new }

before do
    login_as(user, :scope => :user)
end

scenario 'completing quote data' do
    new_quote_form.visit_page.fill_in_with().submit
    expect(page).to have_content('Quote request created')
end
</code>```

here's the model test that passes whilst model validation is present, quote_spec.rb;

```<code>    context 'previous cover' do
        it 'must be true or false' do
            quote = Quote.new(prev_cover: nil)
            quote.valid?
            expect(quote.errors[:prev_cover]).not_to be_empty
        end
    end
</code>```

Failing test message:

```<code>1) creating quote request completing quote data
 Failure/Error: expect(page).to have_content('Quote request created')
   expected to find text "Quote request created" in "Toggle navigation QuoteEngine My Quotes My Account Sign out Complete the below to get a quote * GLA Previous coverYesNois not included in the list * Company name * Company number * Postcode * Industry Financial services Architect Business consultancy Lives overseasYesNo Scheme start date 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 January February March April May June July August September October November December 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Payment frequency Annually Monthly Commission level"
 # ./spec/features/create_quote_spec.rb:14:in `block (2 levels) in <top (required)>'
</code>```

Note the YesNois not included in the list in the error message, using any variation of true or false in the Capybara instruction does not work either.

Even specifying:

```<code><%= f.input :prev_cover, as: :radio_buttons, :collection => [['Yes', true],
                                    ['No', false]], label: "Previous cover" %>
</code>```

in the simpl_form_for in the new.html.erb view still results in the failure with the validation giving Previous coverYesNois not included in the list!?

Even within(".quote_prev_cover") { choose('quote_prev_cover_false') } still fails with the same Previous coverYesNois not included in the list.

It passes if told to choose Yes within(".quote_prev_cover") { choose('Yes') }, almost asif I hadn't already changed from presence: to inclusion: which I most certainly have done.

Actual HTML from firefox inspector:

```<code><div class="form-group radio_buttons optional quote_prev_cover">
  <label class="control-label radio_buttons optional">Previous cover</label>
    <input name="quote[prev_cover]" value="" type="hidden">
        <span class="radio">
            <label for="quote_prev_cover_true">
                <input class="radio_buttons optional" value="true" name="quote[prev_cover]" id="quote_prev_cover_true" type="radio">Yes</label>
        </span>
        <span class="radio">
            <label for="quote_prev_cover_false">
                <input class="radio_buttons optional" readonly="readonly" value="false" name="quote[prev_cover]" id="quote_prev_cover_false" type="radio">No</label>
        </span>
    </div>
</code>```

答:
The only way this report makes sense is if your statement "In actual manual browser testing the db record is created when either Yes or No is selected with corresponding boolean values created just fine." isn't true.

That's because you're using validates_presence_of (through validates presence:{...} shortcut) validator which can't be used with boolean fields if false is a valid response.  From the validates_presence_of docs

If you want to validate the presence of a boolean field (where the
  real values are true and false), you will want to use
  validates_inclusion_of :field_name, in: [true, false].

This is due to the way Object#blank? handles boolean values:
  false.blank? # => true.

Therefore, if you change from presence validation to

```<code>validates :prev_cover, inclusion: { in: [true, false] }
</code>```

your tests will probably pass.

Body:
I have a form with a radio button for a boolean attr prev_cover, displays Yes or No in browser with param values of true or false and saved in db as true or false as data type boolean. I am trying to:

a) model test presence of a selection of the radio buttons

b) feature test the creation of a whole quote record.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('No') } the create_quote_spec test fails, model quote.rb test passes.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('Yes') } the create_quote_spec test passes, model quote.rb test passes.

In actual manual browser testing the db record is created when either Yes or No is selected.

When I remove presence validation of prev_cover from quote.rb the create_quote_spec passes with with prev_cover Yes or No selected, but of course the model quote_spec.rb test fails.

I cannot see where the problem is here, is it something to do with the capybara within(".quote_prev_cover") { choose('No') } syntax perhaps? (it finds that css element just fine)

Here's form element of new.html.erb

            <%= simple_form_for @quote do |f| %>
                <%= f.input :prev_cover, as: :radio_buttons, label: "Previous cover" %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>

Here's quote.rb validation;

validates :prev_cover, inclusion: { in: [true, false] }

Here's prev_cover element of the called NewQuoteFrom.new being created by Capybara;

within(".quote_prev_cover") { choose('No') }

Here's test that fails if chooses prev_cover 'No' and passes if chooses 'Yes', create_quote_spec.rb

feature 'creating quote request' do
let(:user) { FactoryGirl.create(:user) }
let(:new_quote_form) { NewQuoteForm.new }

before do
    login_as(user, :scope => :user)
end

scenario 'completing quote data' do
    new_quote_form.visit_page.fill_in_with().submit
    expect(page).to have_content('Quote request created')
end

here's the model test that passes whilst model validation is present, quote_spec.rb;

    context 'previous cover' do
        it 'must be true or false' do
            quote = Quote.new(prev_cover: nil)
            quote.valid?
            expect(quote.errors[:prev_cover]).not_to be_empty
        end
    end

Failing test message:

1) creating quote request completing quote data
 Failure/Error: expect(page).to have_content('Quote request created')
   expected to find text "Quote request created" in "Toggle navigation QuoteEngine My Quotes My Account Sign out Complete the below to get a quote * GLA Previous coverYesNois not included in the list * Company name * Company number * Postcode * Industry Financial services Architect Business consultancy Lives overseasYesNo Scheme start date 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 January February March April May June July August September October November December 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Payment frequency Annually Monthly Commission level"
 # ./spec/features/create_quote_spec.rb:14:in `block (2 levels) in <top (required)>'

Note the YesNois not included in the list in the error message, using any variation of true or false in the Capybara instruction does not work either.

Even specifying:

<%= f.input :prev_cover, as: :radio_buttons, :collection => [['Yes', true],
                                    ['No', false]], label: "Previous cover" %>

in the simpl_form_for in the new.html.erb view still results in the failure with the validation giving Previous coverYesNois not included in the list!?

Even within(".quote_prev_cover") { choose('quote_prev_cover_false') } still fails with the same Previous coverYesNois not included in the list.

It passes if told to choose Yes within(".quote_prev_cover") { choose('Yes') }, almost asif I hadn't already changed from presence: to inclusion: which I most certainly have done.

Actual HTML from firefox inspector:

  Previous cover
    <input name="quote[prev_cover]" value="" type="hidden">

                <input class="radio_buttons optional" value="true" name="quote[prev_cover]" id="quote_prev_cover_true" type="radio">Yes

                <input class="radio_buttons optional" readonly="readonly" value="false" name="quote[prev_cover]" id="quote_prev_cover_false" type="radio">No

Body:
The only way this report makes sense is if your statement "In actual manual browser testing the db record is created when either Yes or No is selected with corresponding boolean values created just fine." isn't true.

That's because you're using validates_presence_of (through validates presence:{...} shortcut) validator which can't be used with boolean fields if false is a valid response.  From the validates_presence_of docs

If you want to validate the presence of a boolean field (where the
  real values are true and false), you will want to use
  validates_inclusion_of :field_name, in: [true, false].

This is due to the way Object#blank? handles boolean values:
  false.blank? # => true.

Therefore, if you change from presence validation to

validates :prev_cover, inclusion: { in: [true, false] }

your tests will probably pass.


问:
TensorFlow Convolution code Optimization
I am using C++ version of TensorFLow and have built 'TensorFlow for Android' successfully using below command
'bazel build -c opt //tensorflow/examples/android:tensorflow_demo'
as described in https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android#bazel

I am trying to optimize the convolution code. Below are the issues faced

Unable to find the exact location of convolution code.
I am able to debug the code till below function in

'return choose(
Cond(),
kernel.reshape(kernel_dims)
.contract(input
.extract_image_patches(
kernelRows, kernelCols, row_stride, col_stride,
row_in_stride, col_in_stride, padding_type)
.reshape(pre_contract_dims),
contract_dims)
.reshape(post_contract_dims),
input
.extract_image_patches(kernelRows, kernelCols, row_stride, col_stride,
row_in_stride, col_in_stride, padding_type)
.reshape(pre_contract_dims)
.contract(kernel.reshape(kernel_dims), contract_dims)
.reshape(post_contract_dims));'

as present in https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/eigen_spatial_convolutions.h

I have few questions related to the above function.

1.1 Is the above function really performing convolution ? If so where is the code ?

1.2 Is contraction (contract function ) same as convolution ? If both convolution and contraction are same, why is the contract operation being performed to both input and kernel matrix ?

1.3 Where are the definitions of functions - choose, reshape, contract ,extract image patches etc ?

2.Unable to extract data (matrices ) from input and kernel matrix .This is in reference to the same page in the above link

2.1 I have found a line of code 'kern(kernel);' at line no 946 in the above page. Can I know the location definition of the above function ?

2.2 I am unable to extract input and kernel matrices from the corresponding 4d tensors(input and kernel) as a float array, as i would like to try optimizing the convolution code using parallel processing. I couldn't find any method to convert Tensor Matrices from Tensor 4D to an array.

Please help me in answering the above questions

答: Its picking from the eigen TensorFlow files from cache of Linux.My path was /.cache/bazel/_bazel_ashok/c54b442ed4139c7d8ad47f330eb538d6/external/eigen_archive</p>


问:
Show alert if user selects a date within the next 3 days
Im using xdsoft datetimepicker so users can select a deadline. I would like to show an alert if they choose one of the next 3 days.

Initially I had set a minDate so these days were not selectable but I would prefer if these days can be selected and an alert box is shown instead.

I am not sure if there if an option for this already exists, I could not find one in the documentation.

This is how I've been doing it-

html

```<code><h3>Deadline:</h3>
<input type="text" id="datetimepicker"/>
</code>```

jquery

```<code>$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/04',
});
</code>```

I have also set up a jsfiddle

Thanks guys, if you could steer me in the right path it would be much appreciated

答:
Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
}

$("#datetimepicker").on("change", function(){
    var date= new Date().addDays(3);
    var selected = new Date($(this).val());
    var current = new Date();
    if(selected > current && selected < date)
    {
        // your code here
        alert("success");

    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h3>Deadline:</h3>
<input type="date" id="datetimepicker"/></code>```

Body:
Im using xdsoft datetimepicker so users can select a deadline. I would like to show an alert if they choose one of the next 3 days.

Initially I had set a minDate so these days were not selectable but I would prefer if these days can be selected and an alert box is shown instead.

I am not sure if there if an option for this already exists, I could not find one in the documentation.

This is how I've been doing it-

html

Deadline:

<input type="text" id="datetimepicker"/>

jquery

$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/04',
});

I have also set up a jsfiddle

Thanks guys, if you could steer me in the right path it would be much appreciated

Body:
Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
}

$("#datetimepicker").on("change", function(){
    var date= new Date().addDays(3);
    var selected = new Date($(this).val());
    var current = new Date();
    if(selected > current && selected < date)
    {
        // your code here
        alert("success");

    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h3>Deadline:</h3>
<input type="date" id="datetimepicker"/>


问:
Does Empty Azure App Service Plan Cost Anything?
I have deleted all web-apps inside the plan, can I retain the app service plan for later use?</p>

答:
Yes you can. Just make sure it is scaled back to the Free tier so that it does not cost you. You can do this via script or on the Scale-Up menu option from the App Service plan in the portal.

You can find the App Service plan pricing here.


问:
Datepicker textfield edit uneditable
I have a DatePicker with the following code :

```<code>    datepicker.getEditor().addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
        datepicker.show();
    }
    );
</code>```

When clicked on the textfield, the popup appears.
Datepicker popup open

The problem is that i can't type a number in the textfield when the popup is shown.
is it a problem of focus ?
thanks for your help.

答:
As I understand it, you can select a date from the popup, but you can't type anything in the textbox manually. It's editable problem.

In FXML, add editable="true" to your TextField tag. Or check the "Editable" checkbox in Scene Builder. I hope so it can help to you.

Have a nice coding :)

Title: Datepicker textfield edit uneditable

Body:
I have a DatePicker with the following code :

    datepicker.getEditor().addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
        datepicker.show();
    }
    );

When clicked on the textfield, the popup appears.
Datepicker popup open

The problem is that i can't type a number in the textfield when the popup is shown.
is it a problem of focus ?
thanks for your help.


问:
CSS columns not working with images
I have four images with different heights and I would like to do a masonry-like column grid using CSS columns. The following CodePen example doesn't fill the third column when setting columns to 3:

https://codepen.io/glennreyes/pen/pwjOmy

.columns {
  columns: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="columns">
  <img class="image" src="http://lorempixel.com/400/400" alt="" />
  <img class="image" src="http://lorempixel.com/400/500" alt="" />
  <img class="image" src="http://lorempixel.com/400/600" alt="" />
  <img class="image" src="http://lorempixel.com/400/400" alt="" />
</div></code>```

I want three images at the top and the fourth image to one column underneath. What am I missing to fill the content from top/left to bottom/right in a masonry style correctly?

答:
It appears that the source of the problem is the display value of the images.

Images are, by default, display: inline.

If you switch them to display: block, the column property works.

revised codepen

Title: CSS columns not working with images

Body:
I have four images with different heights and I would like to do a masonry-like column grid using CSS columns. The following CodePen example doesn't fill the third column when setting columns to 3:

https://codepen.io/glennreyes/pen/pwjOmy

.columns {
  columns: 3;
}

I want three images at the top and the fourth image to one column underneath. What am I missing to fill the content from top/left to bottom/right in a masonry style correctly?


问:
comparing values associates with same string
I am trying to compare values in column 2 with values in column 3, across the rows. The comparison is not between values in column 2 and 3 in the same row.
The conditions for comparison are:

(1) Value in col2 in one row is to be compared with value in col 3 in another row, when these rows have same string in column 1.

(2) Comparison only when the string in column 1 is repeated at least twice.

(3) Value in column 2 is greater than value in column 3 in a different row, when both rows have same string in column 1.

An example input file is:

```
john    0   100
john    120 200
smith   1   400
claris  300 500
claris  510 700
claris  300 500
dexter  10  400
dexter  100 300
sam 200 300
sam 310 500
tom 100 300
bruce   200 500
bruce   520 900
```

Desired output

```
john    0   100
john    120 200
claris  300 500
claris  510 700
claris  300 500
sam 200 300
sam 310 500
bruce   200 500
bruce   520 900
```

Rows with ‘dexter’  in col1 are not printed. ‘dexter’  is present in two rows but values in col 2 are smaller than values in col3 in other rows, i.e. 10 is less than  300 and 100 is less than 400. While rows with ‘bruce’ are printed because; because 2nd row with bruce has 520 in col 2 which is bigger than 500 in col3 in other row.

I tried it with awk, an example is below. Looks like I can not figure out comparing col2 with col3 in another rows, which have same string in col1

```<code>awk -F "\t" 'NR==FNR{a[$1]++; b[$1]=$2; c[$1]=$3;next}   {for (i in b) if (a[$1] >2 && b[i]>c[i] ) print}' test.file test.file
</code>```

I also tried to it in steps, first by printing only repeated lines and then comparing the associated values.
I am not able to figure out how to compare the values associated with the same string.

答:
As you did in your attempt, we make two passes over the file. In the first, we capture for each person the number of occurrences along with their max value for column_2 and min value for column_3. For the second pass we simply test the given condition for printing.

```<code>NR == FNR {
    if (a[$1]) {
        # we've seen this value before in column_1
        # update the min and max values if necessary
        if ($2 > col2max[$1]) col2max[$1] = $2
        if ($3 < col3min[$1]) col3min[$1] = $3
    }
    else {
        # first time we've seen this value in column_1
        # initial the min and max to the current values
        col2max[$1] = $2
        col3min[$1] = $3
    }
    ++a[$1]
    next
}
a[$1] > 1 && col2max[$1] > col3min[$1]
</code>```

Output:

```<code>$ awk -f a.awk file file
john    0   100
john    120 200
claris  300 500
claris  510 700
claris  300 500
sam 200 300
sam 310 500
bruce   200 500
</code>```

Body:
I am trying to compare values in column 2 with values in column 3, across the rows. The comparison is not between values in column 2 and 3 in the same row.
The conditions for comparison are:

(1) Value in col2 in one row is to be compared with value in col 3 in another row, when these rows have same string in column 1.

(2) Comparison only when the string in column 1 is repeated at least twice.

(3) Value in column 2 is greater than value in column 3 in a different row, when both rows have same string in column 1.

An example input file is:

john    0   100
john    120 200
smith   1   400
claris  300 500
claris  510 700
claris  300 500
dexter  10  400
dexter  100 300
sam 200 300
sam 310 500
tom 100 300
bruce   200 500
bruce   520 900

Desired output

john    0   100
john    120 200
claris  300 500
claris  510 700
claris  300 500
sam 200 300
sam 310 500
bruce   200 500
bruce   520 900

Rows with ‘dexter’  in col1 are not printed. ‘dexter’  is present in two rows but values in col 2 are smaller than values in col3 in other rows, i.e. 10 is less than  300 and 100 is less than 400. While rows with ‘bruce’ are printed because; because 2nd row with bruce has 520 in col 2 which is bigger than 500 in col3 in other row.

I tried it with awk, an example is below. Looks like I can not figure out comparing col2 with col3 in another rows, which have same string in col1

awk -F "\t" 'NR==FNR{a[$1]++; b[$1]=$2; c[$1]=$3;next}   {for (i in b) if (a[$1] >2 && b[i]>c[i] ) print}' test.file test.file

I also tried to it in steps, first by printing only repeated lines and then comparing the associated values.
I am not able to figure out how to compare the values associated with the same string.

Body:
As you did in your attempt, we make two passes over the file. In the first, we capture for each person the number of occurrences along with their max value for column_2 and min value for column_3. For the second pass we simply test the given condition for printing.

NR == FNR {
    if (a[$1]) {
        # we've seen this value before in column_1
        # update the min and max values if necessary
        if ($2 > col2max[$1]) col2max[$1] = $2
        if ($3 < col3min[$1]) col3min[$1] = $3
    }
    else {
        # first time we've seen this value in column_1
        # initial the min and max to the current values
        col2max[$1] = $2
        col3min[$1] = $3
    }
    ++a[$1]
    next
}
a[$1] > 1 && col2max[$1] > col3min[$1]

Output:

$ awk -f a.awk file file
john    0   100
john    120 200
claris  300 500
claris  510 700
claris  300 500
sam 200 300
sam 310 500
bruce   200 500


问:
Calculate Number of worked_days in Given month from Deployment data (Mysql/PHP)
I am working on Payroll System where an employee can be deployed on projects from any_date to any_date. Sample MySQL table below

```<code>id   empid  project_id     start_date                end_date
1      1       2        2016-11-05 15:10:22    2016-12-11 15:11:21
2      1       3        2016-12-13 15:26:10    2016-12-20 15:29:40
3      1       2        2016-12-23 15:31:46    2017-01-18 15:32:35
</code>```

Now, if I want to calculate the number of days in given month worked on all projects, I am using Eloquent which translates to below query(I verified in DB::getQueryLog()):

```<code>SELECT
*
FROM
    payroll_project_tracks
WHERE
    empid = 1
        AND '2016-12-01 00:00:00' BETWEEN start_date AND end_date
        AND '2016-12-31 23:59:59' BETWEEN start_date AND end_date
</code>```

After getting the rows that have deployments of given month (month = Dec 2016 here), I want to calculate Number of Days worked on all projects in a given month.

I am getting no results with the above query. Can anyone correct me or let me know if there is some better way of doing this.

答:
I think that the query should be:

```<code>SELECT *
FROM payroll_project_tracks
WHERE
     empid = 1 AND
     start_date <= '2016-12-31 23:59:59' AND
     end_date >= '2016-12-01 00:00:00'
</code>```

This query will return the 3 rows you provided, but will cut out the following:

```<code>4   1   2   2017-01-01 15:31:46 2017-01-18 15:32:35
</code>```

is this ok?

Body:
I am working on Payroll System where an employee can be deployed on projects from any_date to any_date. Sample MySQL table below

id   empid  project_id     start_date                end_date
1      1       2        2016-11-05 15:10:22    2016-12-11 15:11:21
2      1       3        2016-12-13 15:26:10    2016-12-20 15:29:40
3      1       2        2016-12-23 15:31:46    2017-01-18 15:32:35

Now, if I want to calculate the number of days in given month worked on all projects, I am using Eloquent which translates to below query(I verified in DB::getQueryLog()):

SELECT
*
FROM
    payroll_project_tracks
WHERE
    empid = 1
        AND '2016-12-01 00:00:00' BETWEEN start_date AND end_date
        AND '2016-12-31 23:59:59' BETWEEN start_date AND end_date

After getting the rows that have deployments of given month (month = Dec 2016 here), I want to calculate Number of Days worked on all projects in a given month.

I am getting no results with the above query. Can anyone correct me or let me know if there is some better way of doing this.

Body:
I think that the query should be:

SELECT *
FROM payroll_project_tracks
WHERE
     empid = 1 AND
     start_date <= '2016-12-31 23:59:59' AND
     end_date >= '2016-12-01 00:00:00'

This query will return the 3 rows you provided, but will cut out the following:

4   1   2   2017-01-01 15:31:46 2017-01-18 15:32:35

is this ok?


问:
The ')' character, hexadecimal value 0x29, cannot be included in a name
I am facing an issue by programmatically setting a formula for a sharepoint calculated field, here is the xml that I generate:

```<code><Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
  <Formula>=IF(AND(CampoA>CampoB,CampoA<CampoC),"OK","Not OK")</Formula>
  <FieldRefs>
    <FieldRef Name='CampoC'/>
    <FieldRef Name='CampoB'/>
    <FieldRef Name='CampoA'/>
  </FieldRefs>
</Field>
</code>```

And it gives me the error: The ')' character, hexadecimal value 0x29, cannot be included in a name. Do I have to escape parenthesis?

答:
Inside the Formula element, you need to escape the < with <...

```<code><Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
 <Formula>=IF(AND(CampoA>CampoB,CampoA<CampoC),"OK","Not OK")</Formula>
 <FieldRefs>
  <FieldRef Name='CampoC'/>
  <FieldRef Name='CampoB'/>
  <FieldRef Name='CampoA'/>
 </FieldRefs>
</Field>
</code>```

If you had literal & characters you would also need to escape those with &.

Another option is to wrap the content in CDATA...

```<code><Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
    <Formula><![CDATA[=IF(AND(CampoA>CampoB,CampoA<CampoC),"OK","Not OK")]]></Formula>
    <FieldRefs>
        <FieldRef Name='CampoC'/>
        <FieldRef Name='CampoB'/>
        <FieldRef Name='CampoA'/>
    </FieldRefs>
</Field>
</code>```

I'm not sure if you'd want literal " in your formula. If not, change those to " in the CDATA section.

Body:
I am facing an issue by programmatically setting a formula for a sharepoint calculated field, here is the xml that I generate:

<Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
  <Formula>=IF(AND(CampoA>CampoB,CampoA<CampoC),"OK","Not OK")</Formula>
  <FieldRefs>
    <FieldRef Name='CampoC'/>
    <FieldRef Name='CampoB'/>
    <FieldRef Name='CampoA'/>
  </FieldRefs>
</Field>

And it gives me the error: The ')' character, hexadecimal value 0x29, cannot be included in a name. Do I have to escape parenthesis?

Body:
Inside the Formula element, you need to escape the < with &lt;...

<Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
 <Formula>=IF(AND(CampoA>CampoB,CampoA&lt;CampoC),&quot;OK&quot;,&quot;Not OK&quot;)</Formula>
 <FieldRefs>
  <FieldRef Name='CampoC'/>
  <FieldRef Name='CampoB'/>
  <FieldRef Name='CampoA'/>
 </FieldRefs>
</Field>

If you had literal & characters you would also need to escape those with &amp;.

Another option is to wrap the content in CDATA...

<Field ID='3bc3a7ac-a5bc-49e0-b430-a987ddac42f7' Type='Calculated' Name='Comparison' StaticName='Comparison' DisplayName='Comparison' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>
    <Formula><![CDATA[=IF(AND(CampoA>CampoB,CampoA<CampoC),&quot;OK&quot;,&quot;Not OK&quot;)]]></Formula>
    <FieldRefs>
        <FieldRef Name='CampoC'/>
        <FieldRef Name='CampoB'/>
        <FieldRef Name='CampoA'/>
    </FieldRefs>
</Field>

I'm not sure if you'd want literal &quot; in your formula. If not, change those to " in the CDATA section.


问:
Spring Integration Feed Inbound Channel Adapter duplicate entries
I am using Spring Integration to consume RSS feeds using its inbound channel adapter and writing the feeds to a database table.

To prevent duplicate entries when the process is stopped/started, I have enabled the PropertiesPersistingMetadataStore. As a secondary measure, on the database table, I also have a unique constraint across the feed id/feed entry link columns.

This seems to be working fine but I have noticed on some restarts (not all the time) that I am getting some DB exception errors where it is trying to insert the same RSS feed item again.

Under what conditions would I being getting these duplicate errors and is there anyway I can get round them?

答:
The PropertiesPersistingMetadataStore only persists its state on a normal application shutdown (when the bean is destroy()ed by the application context).

However, it implements Flushable so you can either call flush() on it in your flow after persisting.

You could use transaction synchronization to flush the store after the db transaction commits with the after commit expression @metadataStore.flush().

Or, you could use a more robust persistent store, such as Redis, which persists on each update.


问:
regular expression to delete entire content of file if string matches
I am trying to find a regular expression which would allow me to delete entire content of a file if a particular string matches.

As an example, my file contents are:

```<code>This is the first line
Here is password=SECRET second line
Here is third line
</code>```

I am doing search for string with pattern password= and when that match happens, ALL lines should be removed from the above file.

Below command does remove the entire line matching the pattern but I can't figure out a regular expression for removing the entire content:

```<code>cat test.txt | sed 's|^.*password=.*||'
</code>```

I understand sed works line by line and unless I use additional options in sed, I probably do not have a way to delete the entire content.

The reason I am only interested in regular expression is that I am using another tool which uses regular expression as an input to perform transformations. I use sed here as an example to illustrate what I understand so far.

答:
You said it should delete entire content. But is .* matching entire content ?

I think you should use [\s\S] instead of .

Regex: ^[\s\S]*?password=[\s\S]*

Regex101 Demo

Body:
I am trying to find a regular expression which would allow me to delete entire content of a file if a particular string matches.

As an example, my file contents are:

This is the first line
Here is password=SECRET second line
Here is third line

I am doing search for string with pattern password= and when that match happens, ALL lines should be removed from the above file.

Below command does remove the entire line matching the pattern but I can't figure out a regular expression for removing the entire content:

cat test.txt | sed 's|^.*password=.*||'

I understand sed works line by line and unless I use additional options in sed, I probably do not have a way to delete the entire content.

The reason I am only interested in regular expression is that I am using another tool which uses regular expression as an input to perform transformations. I use sed here as an example to illustrate what I understand so far.


问:
BLOB Storage - 100+ GB, MySQL, SQLite, or PostgreSQL + Python
I have an idea for a simple application which will monitor a group of folders, index any files it finds. A gui will allow me quickly tag new files and move them into a single database for storage and also provide an easy mechanism for querying the db by tag, name, file type and date. At the moment I have about 100+ GB of files on a couple removable hard drives, the database will be at least that big. If possible I would like to support full text search of the embedded binary and text documents. This will be a single user application.

Not trying to start a DB war, but what open source DB is going to work best for me? I am pretty sure SQLLite is off the table but I could be wrong.

答: why are you wasting time emulating something that the filesystem should be able to handle? more storage + grep is your answer.</p>

OwnerDisplayName: Ethan Post

LastEditorDisplayName: Eddie

OwnerDisplayName: nothoh

ContentLicense: CC BY-SA 2.5


问:
How do I count checked checkboxes across all pages of a gridview using jquery?
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview.  Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.

Here is my code:

```<code>$(document).ready(initAll);

function initAll(){
   countChecked();
    $(".activeBoxes").click(countChecked);
}

function countChecked() {

      var n = $(".activeBoxes input:checked").length;
      $("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page.  ");
      if( n == 0){
           $(".activateButton").hide();
           $("#checkboxStatus").hide();

      }else{
        $("#checkboxStatus").show();
        $(".activateButton").show();
      }

}
</code>```

答:
I am using a viewstate to keep track of all checked items across all pages and rechecking them upon returning to the page.

I will have to add my viewstate value to the page total and somehow subtract overlapping totals.  Since my jquery does not include an id, this will be tricky.

```<code>protected ArrayList savedIds;
 if (ViewState["SavedIds"] == null) savedIds = new ArrayList();
        else savedIds = (ArrayList)ViewState["SavedIds"];

List<int> activateList = new List<int>();

        foreach (GridViewRow tt in GridView2.Rows)
        {
            CheckBox cb = (CheckBox)tt.FindControl("ActivateItem");
            HiddenField id = (HiddenField)tt.FindControl("IdField");
            if (cb.Checked)
            {
                int tempId = 0;
                string tempId2 = id.Value.ToString();
                int.TryParse(tempId2, out tempId);
                activateList.Add(tempId);
            }

        }
        foreach (int activateId in activateList)
        {
            if (!savedIds.Contains(activateId.ToString())) savedIds.Add(activateId.ToString());
        }
        ViewState["SavedIds"] = savedIds;
</code>```

OwnerDisplayName: Bryan

Body:
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview.  Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.

Here is my code:

$(document).ready(initAll);

function initAll(){
   countChecked();
    $(".activeBoxes").click(countChecked);
}

function countChecked() {

      var n = $(".activeBoxes input:checked").length;
      $("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page.  ");
      if( n == 0){
           $(".activateButton").hide();
           $("#checkboxStatus").hide();

      }else{
        $("#checkboxStatus").show();
        $(".activateButton").show();
      }

}

LastEditorDisplayName: Jonathan Leffler

Body:
I am using a viewstate to keep track of all checked items across all pages and rechecking them upon returning to the page.

I will have to add my viewstate value to the page total and somehow subtract overlapping totals.  Since my jquery does not include an id, this will be tricky.

protected ArrayList savedIds;
 if (ViewState["SavedIds"] == null) savedIds = new ArrayList();
        else savedIds = (ArrayList)ViewState["SavedIds"];

List<int> activateList = new List<int>();

        foreach (GridViewRow tt in GridView2.Rows)
        {
            CheckBox cb = (CheckBox)tt.FindControl("ActivateItem");
            HiddenField id = (HiddenField)tt.FindControl("IdField");
            if (cb.Checked)
            {
                int tempId = 0;
                string tempId2 = id.Value.ToString();
                int.TryParse(tempId2, out tempId);
                activateList.Add(tempId);
            }

        }
        foreach (int activateId in activateList)
        {
            if (!savedIds.Contains(activateId.ToString())) savedIds.Add(activateId.ToString());
        }
        ViewState["SavedIds"] = savedIds;


问:
Is there an allocator that uses alloca and is otherwise C++ STL compliant?
I have two questions:

1) Is it possible to implement an allocator that uses alloca to allocate memory on the stack and is otherwise C++ STL compliant?

If there is code out there, you can make me happy by simply pointing me to the URL. :-)
If there is no code out there, perhaps you can sketch the functions allocate and deallocate?

2) If the answer to the above question is 'yes', I'd like to understand how it is possible to allocate memory on the stack for class members. As an example, consider an

```<code>std::vector<int, AllocaAllocator<int> >
</code>```

and suppose that a call of the member function 'resize' of this vector calls first 'deallocate' and then 'allocate' of the allocator.

The scope from which allocate is called is that of the member function resize. Doesn't this mean that the allocated memory is removed from the stack at the end of that function call?

Kind regards,
Bjoern

答:
No, this kind of thing isn't possible. For a start, the STL expects to allocate more memory, then free the old memory. How are you going to do that on the stack?

The only thing even remotely equivalent to this is a conservative garbage collector.

Body:
I have two questions:

1) Is it possible to implement an allocator that uses alloca to allocate memory on the stack and is otherwise C++ STL compliant?

If there is code out there, you can make me happy by simply pointing me to the URL. :-)
If there is no code out there, perhaps you can sketch the functions allocate and deallocate?

2) If the answer to the above question is 'yes', I'd like to understand how it is possible to allocate memory on the stack for class members. As an example, consider an

std::vector<int, AllocaAllocator<int> >

and suppose that a call of the member function 'resize' of this vector calls first 'deallocate' and then 'allocate' of the allocator.

The scope from which allocate is called is that of the member function resize. Doesn't this mean that the allocated memory is removed from the stack at the end of that function call?

Kind regards,
Bjoern


问:
How to access Javascript in a completely separate webpacked app
I'm working on an existing large client side web app, transpiled with Babel and Webpacked.

I'm writing a separate small project that needs to tap into the existing code, but without access to it in the local filesystem. This is a Node/web app that will work as a test harness to allow remote developers to create assets that interface with our app. What I need to do is be able to import and use any JS classes that the main app exports / uses, without having that code on the local filesystem.

The answers to this question point to using the library option in the output section of webpack config:
Calling webpacked code from outside (HTML script tag)

I've used the suggestion below the main answer for multiple entry points in one of the comments, eg:
"We have multiple entry points, so in the output section, I instead made it library: ["GlobalAccess", "[name]"],. That then make the var be an object with members for each entrypoint: GlobalAccess.EntryPointFoo, GlobalAccess.EntryPointBar, etc"

My output section looks like this:

```<code>output: {
    // the name of the output file (i.e. same as the input file)
    path: './',
    library: ['GlobalAccess', '[name]'],
    filename: '[name].js'
}
</code>```

However, after doing a build, the output chunks from Webpack are exactly the same as without this option. There are no occurrences of 'GlobalAccess' in any files produced. What should I see in the output chunks that tells me its worked?? The official documentation is pretty sparse..
https://webpack.js.org/configuration/output/#output-library
but this example shows how to set a library up so every entry has a different namespace:
https://github.com/webpack/webpack/tree/master/examples/multi-part-library

答:
Well, in case anyone else ever comes across this question, which admittedly is a bit of a strange one, I did the following:

Convert the Webpack build to a library, with 'umd' as the library target

Upgrade Webpack from v1.14 to v2.x in order to use export default class instead of just module.exports

Turn off Uglification and Chunking

So that meant I could have a big project compiled in one place using Webpack, and the resulting output file can be imported and used in a completely different project without access to the original.

Body:
I'm working on an existing large client side web app, transpiled with Babel and Webpacked.

I'm writing a separate small project that needs to tap into the existing code, but without access to it in the local filesystem. This is a Node/web app that will work as a test harness to allow remote developers to create assets that interface with our app. What I need to do is be able to import and use any JS classes that the main app exports / uses, without having that code on the local filesystem.

The answers to this question point to using the library option in the output section of webpack config:
Calling webpacked code from outside (HTML script tag)

I've used the suggestion below the main answer for multiple entry points in one of the comments, eg:
"We have multiple entry points, so in the output section, I instead made it library: ["GlobalAccess", "[name]"],. That then make the var be an object with members for each entrypoint: GlobalAccess.EntryPointFoo, GlobalAccess.EntryPointBar, etc"

My output section looks like this:

output: {
    // the name of the output file (i.e. same as the input file)
    path: './',
    library: ['GlobalAccess', '[name]'],
    filename: '[name].js'
}

However, after doing a build, the output chunks from Webpack are exactly the same as without this option. There are no occurrences of 'GlobalAccess' in any files produced. What should I see in the output chunks that tells me its worked?? The official documentation is pretty sparse..
https://webpack.js.org/configuration/output/#output-library
but this example shows how to set a library up so every entry has a different namespace:
https://github.com/webpack/webpack/tree/master/examples/multi-part-library


问:
How to load html with iframe?
I have:

index.html

and

test.html

and I could load my test.html with jquery load(); function to in index.html

but then my index.html style is broken that is why I want to load my test.html into index.html as iframe..

index.html

load test.html here with iframe

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">
I'm a test div and I want to be in index.html in `item` class
</div></code>```

答:
What you could do is to specify only the content you want to load when using jQuery.load like this:

```<code>$( "#result" ).load( "test.html #container" );
</code>```

Then it would only load the content of #container instead of everything (including the styles which might break your layout.

If you want to change an iframe src with jQuery you could use a click event like so:

```<code>jQuery( function() {
  $( 'button' ).click( function( e ) {
    e.preventDefault();
    $( '#result' ).attr( 'src', 'test.html' );
  } )
} )
</code>```

But I think it would be better to use the first approach, trying to only load the content itself, not the whole HTML structure of test.html.

I hope that helped :)

Title: How to load html with iframe?

Body:
I have:

index.html

and

test.html

and I could load my test.html with jquery load(); function to in index.html

but then my index.html style is broken that is why I want to load my test.html into index.html as iframe..

index.html

load test.html here with iframe

I'm a test div and I want to be in index.html in `item` class

Body:
What you could do is to specify only the content you want to load when using jQuery.load like this:

$( "#result" ).load( "test.html #container" );

Then it would only load the content of #container instead of everything (including the styles which might break your layout.

If you want to change an iframe src with jQuery you could use a click event like so:

jQuery( function() {
  $( 'button' ).click( function( e ) {
    e.preventDefault();
    $( '#result' ).attr( 'src', 'test.html' );
  } )
} )

But I think it would be better to use the first approach, trying to only load the content itself, not the whole HTML structure of test.html.

I hope that helped :)


问:
Plain text encryption issues
I have a database column filled with plain text. The managers decided that it is too risky to store passwords in a database as plain text. So the problem is, that I need to transfer all values in that given column to encrypted text and of course modify the business logic in C#. From know on the program should read the encrypted value from the database, decrypt the data and work with it, and of course if a new user registers I need to store the ecrypted value in the database. (But this does not a problem.)
So is there a proper and secure way to encrypt this whole column (which is already in use as plain text) without breaking the behavior of the software?     </p>

答:
1) Create new column like hash_pwd;

2) Fill it with hashed equivalent of current password;

3) Change software to work with hash, not plain password;

4) Drop or clear the old column with plain passwords.

PS: It is good idea to store not simple hash (MD5/SHA) of password but add static string like HASH( plain_password + "my_string" ). This will protect the database from hash-dictionary hacks - e.g. if I know the result of HASH( "123456" ) and can find all users using password 123456.

ContentLicense: CC BY-SA 4.0

Title: Plain text encryption issues


问:
ReactiveX C#: Do something when subscription starts
I've created an IObservable<> combination using CombineLatest():

```<code>IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations);
</code>```

I need:

```<code>1. to do something `doSomethingOnFirst()` when first element is reached.
2. to do something `doSomethingOnComplete()` when subscription has completed.
</code>```

Up to now, I've been able to do something when combination is completed. Nevertheless, I don't quite figure out what do I need to do in order to do something when subscription starts...

```<code>combination
    .Subscribe(
        _ => { },
        _ => { },
        () => this.doSomethingOnCompleted()
    );
</code>```

Any ideas?

答:
It's probably best to use two subscriptions to accomplish this. When subscribing twice to an observable, it's also best to share a subscription to the source, which can be accomplished with .Publish().RefCount().

```<code>IEnumerable<IObservable<List<TileItem>>> combinations = null /* using null so I can compile /;
IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations)
    .Publish()
    .RefCount();

combination.Take(1)
    .Subscribe(_ => doSomethingOnFirst());

combination.Subscribe(_ => { }, _ => {}, () => doSomethingOnCompleted);
</code>```

You can also accomplish the functionality by filtering the observable by index:

```<code>IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations)
    .Where((item, i) => i == 0)

combination.Subscribe(_ => doSomethingOnFirst(), _ => {}, () => doSomethingOnCompleted);
</code>```

Body:
I've created an IObservable<> combination using CombineLatest():

IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations);

I need:

1. to do something `doSomethingOnFirst()` when first element is reached.
2. to do something `doSomethingOnComplete()` when subscription has completed.

Up to now, I've been able to do something when combination is completed. Nevertheless, I don't quite figure out what do I need to do in order to do something when subscription starts...

combination
    .Subscribe(
        _ => { },
        _ => { },
        () => this.doSomethingOnCompleted()
    );

Any ideas?

Body:
It's probably best to use two subscriptions to accomplish this. When subscribing twice to an observable, it's also best to share a subscription to the source, which can be accomplished with .Publish().RefCount().

IEnumerable<IObservable<List<TileItem>>> combinations = null /* using null so I can compile /;
IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations)
    .Publish()
    .RefCount();

combination.Take(1)
    .Subscribe(_ => doSomethingOnFirst());

combination.Subscribe(_ => { }, _ => {}, () => doSomethingOnCompleted);

You can also accomplish the functionality by filtering the observable by index:

IObservable<IList<List<TileItem>>> combination = Observable.CombineLatest(combinations)
    .Where((item, i) => i == 0)

combination.Subscribe(_ => doSomethingOnFirst(), _ => {}, () => doSomethingOnCompleted);


问:
WPF Bind Checkbox IsChecked to other Checkboxes (IsChecked || !IsEnabled)
I have a select 'All' checkbox that I would like to be bound to the (IsChecked || !IsEnabled) of other checkboxes.

Checking 'All' checks all enabled checkboxes.

Unchecking 'All' unchecks all checkboxes.

Manually checking each enabled checkbox will check 'All'.

When all enabled checkboxes and 'All' are checked and user unchecks any checkbox, 'All' automatically unchecks.

I am new to WPF Databinding.  I was thinking maybe I just handle the click of 'All' to set the other checkboxes.  But I don't know how to bind to both properties of multiple sources.  When I click 'All' and manually uncheck another checkbox, 'All' needs to uncheck.

答:
I'd create a ViewModel behind your View class using the MVVM design pattern: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Then on your ViewModel (which will have to implement INotifyPropertyChanged) you can have multiple bool properties, one for each CheckBox and another for all of them:

```<code>public bool IsChecked1
{
    get
    {
         return isChecked1;
    }
    set
    {
         if (isChecked1 != value)
         {
             isChecked1 = value;
             RaisePropertyChanged("IsChecked1");
             RaisePropertyChanged("AreAllChecked");
         }
    }
}

// And so on

public bool AreAllChecked
{
    get
    {
        return IsChecked1 && IsChecked2; // etc.
    }
    set
    {
        if (AreAllChecked != value)
        {
            IsChecked1 = value;
            IsChecked2 = value;
            // etc.
        }
    }
}
</code>```

Body:
I'd create a ViewModel behind your View class using the MVVM design pattern: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Then on your ViewModel (which will have to implement INotifyPropertyChanged) you can have multiple bool properties, one for each CheckBox and another for all of them:

public bool IsChecked1
{
    get
    {
         return isChecked1;
    }
    set
    {
         if (isChecked1 != value)
         {
             isChecked1 = value;
             RaisePropertyChanged("IsChecked1");
             RaisePropertyChanged("AreAllChecked");
         }
    }
}

// And so on

public bool AreAllChecked
{
    get
    {
        return IsChecked1 && IsChecked2; // etc.
    }
    set
    {
        if (AreAllChecked != value)
        {
            IsChecked1 = value;
            IsChecked2 = value;
            // etc.
        }
    }
}


问:
Jsplumb - Connectors
Am trying to draw a flowchart. I create divs dynamically and have set a unique 'id' property for each div and connect them using Jsplumb connectors.

I get the source and destination id from database(note that 'id' property for div dynamically created is its ID from database) and store in 'connectors' json. Its format is
Eg:

{[from:A,to:B], [from:A,to:C], [from:B,to:C]}

```<code>angular.forEach(connectors, function (connect) {
                        $scope.connection(connect.from, connect.to);
                    })
</code>```

The jsplumb code is as follows

```<code>$scope.connection = function (s, t) {
var stateMachineConnector1 = {
                    connector: ["Flowchart", { stub: 25, midpoint: 0.001 }],
                    maxConnections: -1,
                    paintStyle: { lineWidth: 3, stroke: "#421111" },
                    endpoint: "Blank",
                    anchor: "Continuous",
                    anchors: [strt, end],
                    overlays: [["PlainArrow", { location: 1, width: 15, length: 12 }]]
                };
var firstInstance = jsPlumb.getInstance();
firstInstance.connect({ source: s.toString(), target: t.toString() }, stateMachineConnector1);
    }
</code>```

THE PROBLEM:

What i have now is

Here the connector B to C overlaps existing A to C connector.

What i need is to separate the two connections like below

I could not find a solution for this anywhere. Any help? Thanks!

答:
What I suggest you to do, to exactly replicate your schema, would be to set 2 endpoints on on box on A, B and C

A Endpoints should be [0.25, 1, 0, 0, 0, 0] and [0.75, 1, 0, 0, 0, 0]

B and C Endpoints should be [0.25, 0, 0, 0, 0, 0] and [0.75, 0, 0, 0, 0, 0]

It basically works like this (I might be wrong for the 4 last one its been a while but you only need to worry about the x and y)

[x,y,offsetx, offsety, angle, angle]

For the x 0 is the extreme left and 1 extreme right

Same goes for y (0 is top and 1 is bottom).

Take care

Title: Jsplumb - Connectors

Body:
Am trying to draw a flowchart. I create divs dynamically and have set a unique 'id' property for each div and connect them using Jsplumb connectors.

I get the source and destination id from database(note that 'id' property for div dynamically created is its ID from database) and store in 'connectors' json. Its format is
Eg:

{[from:A,to:B], [from:A,to:C], [from:B,to:C]}

angular.forEach(connectors, function (connect) {
                        $scope.connection(connect.from, connect.to);
                    })

The jsplumb code is as follows

$scope.connection = function (s, t) {
var stateMachineConnector1 = {
                    connector: ["Flowchart", { stub: 25, midpoint: 0.001 }],
                    maxConnections: -1,
                    paintStyle: { lineWidth: 3, stroke: "#421111" },
                    endpoint: "Blank",
                    anchor: "Continuous",
                    anchors: [strt, end],
                    overlays: [["PlainArrow", { location: 1, width: 15, length: 12 }]]
                };
var firstInstance = jsPlumb.getInstance();
firstInstance.connect({ source: s.toString(), target: t.toString() }, stateMachineConnector1);
    }

THE PROBLEM:

What i have now is

Here the connector B to C overlaps existing A to C connector.

What i need is to separate the two connections like below

I could not find a solution for this anywhere. Any help? Thanks!


问:
Running .exe from Java gives different console output then running .exe directly from Windows
So this one is a bit strange - Why running .exe file from Java gives different output as opposed to running .exe directly.

When java executes below line, it invokes an .exe file which i have build that works with 3CX phone system.

```<code>p = Runtime.getRuntime().exec("3cx-api-application/orderly-3cx.exe");
</code>```

When the code is executed from java/eclipse/jar file the below error is printed.

```<code>INFO: 3CX Initialization Started
Jun 08, 2017 1:58:19 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
INFO: Sending: Initializing 3cx-Orderly Connector
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE:
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE: Unhandled Exception: TCX.Configuration.Exceptions.PhoneSystemException: ConfigServer is not connected
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE:    at TCX.Configuration.PhoneSystem.Connect()
</code>```

Now when i navigate to the .exe file directly by going into 3cx-api-application and clicking on orderly-3cx.exe program is executed just fine, giving me below output.

Note: the 'initializing 3cx-orderly connector' line on both outputs.

```<code>Initializing 3cx-Orderly Connector
Program Initialized
Initialize Monitor
*0 NOT REGISTEREDVMB(0/0)
a length: 0
*1 NOT REGISTEREDVMB(0/0)
a length: 0
</code>```

And what is weirder is that, this used to work in java but now it does not. All the .exe file is supposed to do is connect to 3CX API and print some output to console, this output should then be read by java class.

I have cleaned both projects (eclipse/visual studio), re-compiled all classes etc. Still the same issue

答:
The executable file reads a config file from the same directory as itself. You need to run the executable from that directory. See http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#exec-java.lang.String-java.lang.String:A-java.io.File-

Try:

```<code>p = Runtime.getRuntime().exec("orderly-3cx.exe", null, "3cx-api-application");
</code>```

(P.S. Oracle's Javadoc recommends that new applications should use ProcessBuilder instead of Runtime.)

Body:
So this one is a bit strange - Why running .exe file from Java gives different output as opposed to running .exe directly.

When java executes below line, it invokes an .exe file which i have build that works with 3CX phone system.

p = Runtime.getRuntime().exec("3cx-api-application/orderly-3cx.exe");

When the code is executed from java/eclipse/jar file the below error is printed.

INFO: 3CX Initialization Started
Jun 08, 2017 1:58:19 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
INFO: Sending: Initializing 3cx-Orderly Connector
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE:
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE: Unhandled Exception: TCX.Configuration.Exceptions.PhoneSystemException: ConfigServer is not connected
Jun 08, 2017 1:58:28 PM com.orderlysoftware.threecx.Orderly3CXConnector threeCXinit
SEVERE: SEVERE:    at TCX.Configuration.PhoneSystem.Connect()

Now when i navigate to the .exe file directly by going into 3cx-api-application and clicking on orderly-3cx.exe program is executed just fine, giving me below output.

Note: the 'initializing 3cx-orderly connector' line on both outputs.

Initializing 3cx-Orderly Connector
Program Initialized
Initialize Monitor
*0 NOT REGISTEREDVMB(0/0)
a length: 0
*1 NOT REGISTEREDVMB(0/0)
a length: 0

And what is weirder is that, this used to work in java but now it does not. All the .exe file is supposed to do is connect to 3CX API and print some output to console, this output should then be read by java class.

I have cleaned both projects (eclipse/visual studio), re-compiled all classes etc. Still the same issue

Body:
The executable file reads a config file from the same directory as itself. You need to run the executable from that directory. See http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#exec-java.lang.String-java.lang.String:A-java.io.File-

Try:

p = Runtime.getRuntime().exec("orderly-3cx.exe", null, "3cx-api-application");

(P.S. Oracle's Javadoc recommends that new applications should use ProcessBuilder instead of Runtime.)


问:
dll files not getting committed in github
I'm very beginner in using git.
I uploaded my coded to git.But when I do commit, my .dll files are not committing. What might be the reason for this ? did I miss anything ?</p>

答:
Did you set the repo up yourself?  If not, there might be a git ignore rule (such as in the .gitignore file) preventing the .dll files from being committed.  If so, it's likely for good reason; it typically isn't a good idea to commit .dll files for a couple of reasons.

First, they are binary files, and often they are rather large relative to the size of code files in a repo.  This can lead to numerous usability problems.  If you really do have a need to store .dll or similar files, you should consider using git LFS to mitigate the impact.

Second, it just generally isn't necessary.  Dependencies can be fetched as part of a build process (using an in-house artifact repository if absolute guarantees of version stability are needed).  Build products can be regenerated after a checkout.  Storing such binaries is basically all cost and no benefit.

But if you still want to commit them:  Well, if there are ignore rules, you could remove them (though if the repo is shared this should be a team discussion.  Like I said, the most likely place for them would be .gitignore (which is also stored as part of the commit).

If you think there are no ignore rules, you can verify by running git status which will tell you what files git is thinking about in the repo.

If the .dll files are in the work tree but are not listed by git status, then either they're fully up-to-date and checked in or they have an ignore rule.

If they show up as "untracked files", then you would have to git add them before they'd be included in a commit.

If they show up as "new files", they're staged and should be included in a subsequent commit.


问:
Add a custom header to scala WebSocketRequest
I am following the example here to create a websocket client in Scala. I want to pass a custom header in the websocket request. I created a CustomHeader class by extending HttpHeader.

```<code>final class CustomHeader(headerName: String, headerValue: String) extends HttpHeader {
  override def name(): String = headerName

  override def value(): String = headerValue

  override def lowercaseName(): String = name.toLowerCase

  override def renderInRequests(): Boolean = true

  override def renderInResponses(): Boolean = true
}
</code>```

Then in the client,

```<code>val headers = Seq(new CustomHeader("X-Auth-Token", authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
</code>```

When I run activator compile, it throws the following error:

```<code>type mismatch;
[error]  found   : Seq[com.apple.geo.neutron.services.notification.event.CustomHeader]
[error]  required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader]
[error] Error occurred in an application involving default arguments.
[error]     val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
</code>```

How do I resolve this error, or add a custom header to the websocket request?

答:
Seq here is not an immutable Seq. Try defining headers as:

```<code>val headers = scala.collection.immutable.Seq(new CustomHeader("X-Auth-Token", authToken))
</code>```

Body:
I am following the example here to create a websocket client in Scala. I want to pass a custom header in the websocket request. I created a CustomHeader class by extending HttpHeader.

final class CustomHeader(headerName: String, headerValue: String) extends HttpHeader {
  override def name(): String = headerName

  override def value(): String = headerValue

  override def lowercaseName(): String = name.toLowerCase

  override def renderInRequests(): Boolean = true

  override def renderInResponses(): Boolean = true
}

Then in the client,

val headers = Seq(new CustomHeader("X-Auth-Token", authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)

When I run activator compile, it throws the following error:

type mismatch;
[error]  found   : Seq[com.apple.geo.neutron.services.notification.event.CustomHeader]
[error]  required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader]
[error] Error occurred in an application involving default arguments.
[error]     val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)

How do I resolve this error, or add a custom header to the websocket request?

Body:
Seq here is not an immutable Seq. Try defining headers as:

val headers = scala.collection.immutable.Seq(new CustomHeader("X-Auth-Token", authToken))


问:
Display number of days to Sale end on Sale Products page
I got this code from here ( Display woocommerce sale end date )

```<code>add_filter( 'woocommerce_get_price_html', 'custom_price_html', 100, 2 );
function custom_price_html( $price, $product )
{
    global $post;
    $sales_price_to = get_post_meta($post->ID, '_sale_price_dates_to', true);
    if(is_single() && $sales_price_to != "")
    {
        $sales_price_date_to = date("j M y", $sales_price_to);
        return str_replace( '</ins>', ' </ins> <b>(Sale ends '.$sales_price_date_to.')</b>', $price );
    }
    else
    {
        return apply_filters( 'woocommerce_get_price', $price );
    }
}
</code>```

Works well like magic on the product page but I need help for this code to show days to end of sale instead. E.g. Sale ends in 1day/2days/3days etc. as the case may be. And also show on the Sale Products page not only on the Product page.

答:
This code should do the job! Paste it in functions.php

```<code>add_filter( 'woocommerce_get_price_html', 'add_end_sale_to_price', 100, 2 );
function add_end_sale_to_price( $price, $product )
{
    global $post;
    $sales_price_to = get_post_meta($post->ID, '_sale_price_dates_to', true);
    if($sales_price_to != "")
    {
        $now = time();
        $sales_price_date_to = date("Y-m-d", $sales_price_to);
        $end_date = strtotime($sales_price_date_to);
        $days_left = $end_date - $now;
        $days_left = floor($days_left / (60 * 60 * 24));

        return str_replace( '</ins>', ' </ins> <b>(Sale ends in '.$days_left.' days)</b>', $price );
    }
    else
    {
        return apply_filters( 'woocommerce_get_price', $price );
    }
}
</code>```

Cheers,

Francesco

Body:
I got this code from here ( Display woocommerce sale end date )

add_filter( 'woocommerce_get_price_html', 'custom_price_html', 100, 2 );
function custom_price_html( $price, $product )
{
    global $post;
    $sales_price_to = get_post_meta($post->ID, '_sale_price_dates_to', true);
    if(is_single() && $sales_price_to != "")
    {
        $sales_price_date_to = date("j M y", $sales_price_to);
        return str_replace( '', '  (Sale ends '.$sales_price_date_to.')', $price );
    }
    else
    {
        return apply_filters( 'woocommerce_get_price', $price );
    }
}

Works well like magic on the product page but I need help for this code to show days to end of sale instead. E.g. Sale ends in 1day/2days/3days etc. as the case may be. And also show on the Sale Products page not only on the Product page.

Body:
This code should do the job! Paste it in functions.php

add_filter( 'woocommerce_get_price_html', 'add_end_sale_to_price', 100, 2 );
function add_end_sale_to_price( $price, $product )
{
    global $post;
    $sales_price_to = get_post_meta($post->ID, '_sale_price_dates_to', true);
    if($sales_price_to != "")
    {
        $now = time();
        $sales_price_date_to = date("Y-m-d", $sales_price_to);
        $end_date = strtotime($sales_price_date_to);
        $days_left = $end_date - $now;
        $days_left = floor($days_left / (60 * 60 * 24));

        return str_replace( '</ins>', ' </ins> <b>(Sale ends in '.$days_left.' days)</b>', $price );
    }
    else
    {
        return apply_filters( 'woocommerce_get_price', $price );
    }
}

Cheers,

Francesco


问:
How to make undefined many SQL updates
I'm trying to manage a SQLite Database by updating all the average values of two rows (only the floats), which are in a timeinterval. One of the two rows should be deleted after the average values are determind. The SQL-statment I'm looking for, is embbeded in a Pythonscript, which gets one time a day called by a cronjob.

For Example:

Before the Cronjob

```<code>1|Node1|45.39|25.07|1013.3|2.086|2017-06-01 17:43:43
2|Node1|48.07|25.07|1013.4|2.081|2017-06-01 17:43:57
3|Node1|45.37|25.08|1013.3|2.08|2017-06-01 17:44:01
4|Node1|48.04|25.07|1013.3|1.991|2017-06-01 17:44:15
5|Node1|45.39|25.08|1013.3|1.991|2017-06-01 17:48:36
6|Node1|45.47|25.03|1013.4|1.991|2017-06-01 17:50:57
7|Node1|45.48|25.03|1013.3|1.991|2017-06-01 17:52:09
8|Node1|45.46|25.04|1013.3|1.991|2017-06-01 17:53:26
9|Node1|45.25|25.12|1013.3|2.092|2017-06-01 17:57:20
10|Node1|45.43|25.02|1013.2|2.093|2017-06-01 18:03:19
</code>```

After the Cronjob

```<code>1|Node1|46.73|25.07|1013.35|2.084|2017-06-01 17:43:43
2|Node1|46.705|25.075|1013.3|2.081|2017-06-01 17:44:01
3|Node1|45.43|25.055|1013.35|1.999|2017-06-01 17:48:36
4|Node1|48.47|25.035|1013.3|1.991|2017-06-01 17:52:09
5|Node1|45.35|25.07|1013.25|2.092|2017-06-01 17:57:20
</code>```

I'm not really sure how to solve this problem and which is the most efficient way. Of course, it is possible to count the number of rows and loop them for each two rows. In my case this could mean the cronjob do more then 1000 sql-querys, which seems to be not very efficient.

EDIT
Following Pythonclass creates the SQLite-database

```<code>conn = sqlite3.connect('/var/www/sqliteDatabases/database_sdr.db')    #connect to database "database.db"

cur = conn.cursor()
    #create a cursor

    #______create table for temperature and humidity with date and time______
cur.execute('''CREATE TABLE measurement(
                        ID INTEGER PRIMARY KEY AUTOINCREMENT,
                        nodeId text,
                        humidity float,
                        temperature float,
                        pressure float,
                        voltage float,
                        datetime text)''') c

conn.commit() conn.close()
</code>```

EDIT 2:

This is the main.py which gets called one time a day by a cronjob.

```<code>from includes.MyDatabase import MyDatabase
from includes.MyDates import MyDates

uri = '/var/www/sqliteDatabases/database_sdr.db'

dt = MyDates()
db = MyDatabase(uri)
db.sum_up_week(dt.weekago)
db.sum_up_month(dt.monthago)
db.sum_up_year(dt.yearago)
db.close()
</code>```

this is the Database class for updating and deleting the Database (For now the sum_up-function without SQL Statements):

```<code>import sqlite3
import sys

class MyDatabase():

    def __init__(self, uri):
        self.uri = uri
        try:
            self.conn = sqlite3.connect(self.uri)   #connect to database "wsn.db"
            self.cur  = self.conn.cursor()          #create a cursor
        except sqlite3.Error as err:
            print('Database connection failed with this path:'+self.uri+' Error: '), err.args[0]
            exit()

    def sum_up_week(self, week):
        print(week)     #e.g. 2017-06-01

    def sum_up_month(self, month):
        print(month)    #e.g. 2017-05-08

    def sum_up_year(self, year):
        print(year)     #e.g. 2016-06-08

    def close(self):
        self.conn.commit()  #save the determined rows
        self.conn.close()   #close connection to DB
</code>```

答:
To get consecutive ID values, copy everything into a temporary table. Then use a self-join to combine the rows with corresponding even and odd ID values, and copy everything back:

CREATE TEMPORARY TABLE t1 (
    id INTEGER PRIMARY KEY,
    nodeId,
    humidity,
    temperature,
    pressure,
    voltage,
    datetime
);

INSERT INTO t1
SELECT NULL, nodeId, humidity, temperature, pressure, voltage, datetime
FROM measurement;

CREATE TEMPORARY TABLE t2 AS
SELECT a.nodeId                            AS nodeId,
       (a.humidity    + b.humidity   ) / 2 AS humidity,
       (a.temperature + b.temperature) / 2 AS temperature,
       (a.pressure    + b.pressure   ) / 2 AS pressure,
       (a.voltage     + b.voltage    ) / 2 AS voltage,
       a.datetime                          AS datetime
FROM t1 AS a
JOIN t1 AS b ON a.id + 1 = b.id
            AND (a.id % 2) == 1;

DELETE FROM measurement;

INSERT INTO measurement
SELECT NULL, nodeId, humidity, temperature, pressure, voltage, datetime
FROM t2;

DROP TABLE t1;
DROP TABLE t2;
```

Title: How to make undefined many SQL updates

Body:
I'm trying to manage a SQLite Database by updating all the average values of two rows (only the floats), which are in a timeinterval. One of the two rows should be deleted after the average values are determind. The SQL-statment I'm looking for, is embbeded in a Pythonscript, which gets one time a day called by a cronjob.

For Example:

Before the Cronjob

1|Node1|45.39|25.07|1013.3|2.086|2017-06-01 17:43:43
2|Node1|48.07|25.07|1013.4|2.081|2017-06-01 17:43:57
3|Node1|45.37|25.08|1013.3|2.08|2017-06-01 17:44:01
4|Node1|48.04|25.07|1013.3|1.991|2017-06-01 17:44:15
5|Node1|45.39|25.08|1013.3|1.991|2017-06-01 17:48:36
6|Node1|45.47|25.03|1013.4|1.991|2017-06-01 17:50:57
7|Node1|45.48|25.03|1013.3|1.991|2017-06-01 17:52:09
8|Node1|45.46|25.04|1013.3|1.991|2017-06-01 17:53:26
9|Node1|45.25|25.12|1013.3|2.092|2017-06-01 17:57:20
10|Node1|45.43|25.02|1013.2|2.093|2017-06-01 18:03:19

After the Cronjob

1|Node1|46.73|25.07|1013.35|2.084|2017-06-01 17:43:43
2|Node1|46.705|25.075|1013.3|2.081|2017-06-01 17:44:01
3|Node1|45.43|25.055|1013.35|1.999|2017-06-01 17:48:36
4|Node1|48.47|25.035|1013.3|1.991|2017-06-01 17:52:09
5|Node1|45.35|25.07|1013.25|2.092|2017-06-01 17:57:20

I'm not really sure how to solve this problem and which is the most efficient way. Of course, it is possible to count the number of rows and loop them for each two rows. In my case this could mean the cronjob do more then 1000 sql-querys, which seems to be not very efficient.

EDIT
Following Pythonclass creates the SQLite-database

conn = sqlite3.connect('/var/www/sqliteDatabases/database_sdr.db')    #connect to database "database.db"

cur = conn.cursor()
    #create a cursor

    #______create table for temperature and humidity with date and time______
cur.execute('''CREATE TABLE measurement(
                        ID INTEGER PRIMARY KEY AUTOINCREMENT,
                        nodeId text,
                        humidity float,
                        temperature float,
                        pressure float,
                        voltage float,
                        datetime text)''') c

conn.commit() conn.close()

EDIT 2:

This is the main.py which gets called one time a day by a cronjob.

from includes.MyDatabase import MyDatabase
from includes.MyDates import MyDates

uri = '/var/www/sqliteDatabases/database_sdr.db'

dt = MyDates()
db = MyDatabase(uri)
db.sum_up_week(dt.weekago)
db.sum_up_month(dt.monthago)
db.sum_up_year(dt.yearago)
db.close()

this is the Database class for updating and deleting the Database (For now the sum_up-function without SQL Statements):

import sqlite3
import sys

class MyDatabase():

    def __init__(self, uri):
        self.uri = uri
        try:
            self.conn = sqlite3.connect(self.uri)   #connect to database "wsn.db"
            self.cur  = self.conn.cursor()          #create a cursor
        except sqlite3.Error as err:
            print('Database connection failed with this path:'+self.uri+' Error: '), err.args[0]
            exit()

    def sum_up_week(self, week):
        print(week)     #e.g. 2017-06-01

    def sum_up_month(self, month):
        print(month)    #e.g. 2017-05-08

    def sum_up_year(self, year):
        print(year)     #e.g. 2016-06-08

    def close(self):
        self.conn.commit()  #save the determined rows
        self.conn.close()   #close connection to DB


问:
Connection between any sources and google-cloud-Pub/Sub
I'm new to Google cloud platform. I want to know how to connect my client sources data in order that they arrive in the pub/sub system?</p>

答:
That's a really general question, some more specific information from your side could be useful to answer in more detail.

You can start by reading up on some resources:

What is Pub/Sub: gives you a very high-level overview of what Pub/Sub is and does.

Quickstart: helps you on some of the concepts and gets you started using Pub/Sub

More detailed info for actually publishing data to Pub/Sub using the APIs or one of the client libraries can be found in these resources.


问:
Run app on iTouch w/o iTunes
I have written a small app using Ojective-C w/ XCode. It's only for personal fun and I don't want to pay Apple $99 to just let it run on my iTouch. Is there any alternative for me to run it on iTouch instead of iPhone simulator? Please give me some suggestion.</p>

答: Not legally, as you need to register the device, obtain a signing certificate, etc. which is only possible if you're a registered developer.</p>

Title: Run app on iTouch w/o iTunes


问:
How to change button color when radio input is selected, but input is wrapped in div before label?
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5942" onclick="">

    <div class="donation-level-amount-container">
    $35.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5943" onclick="">

    <div class="donation-level-amount-container">
    $60.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5944" onclick="">

    <div class="donation-level-amount-container">
    $120.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
  </div>
</div></code>```

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

答:
You want something like this

```<code>$(".donation-level-amount-container").on("click", function() {
    $(this).css("background", "red");
})
</code>```

or to toggle an active class

```<code>$(".donation-level-amount-container").on("click", function() {
    $(this).toggleClass("active");
})
</code>```

Body:
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">

    $35.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">

    $60.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">

    $120.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

Body:
You want something like this

$(".donation-level-amount-container").on("click", function() {
    $(this).css("background", "red");
})

or to toggle an active class

$(".donation-level-amount-container").on("click", function() {
    $(this).toggleClass("active");
})