问:
How to Match Using sed a Multi-Line Range Defined by More Than Two Bounds?
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

```<code>           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)
</code>```

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

```<code>           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)
</code>```

It also fails if SomeObj.someFunct is on the next line, i.e.:

```<code>           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)
</code>```

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.

答:
This might work for you (GNU sed):

```<code>sed -rn '/^\s*\w+:/!b;:a;N;/\)\s*$/!ba;/^\s*\w+:\s*SomeObj\.someFunct\s*\(/p;//d;D' file
</code>```

This matches on the first variable and then appends further lines until a ) followed by possible white space and the end of a line. The pattern space is then checked to see that all other matches are met and prints the pattern space if so. Othewise the first line is deleted and the process is repeated.

N.B. As stated regexp cannot be used for matching parens in all cases, this should be left to a parser.

Body:
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)

It also fails if SomeObj.someFunct is on the next line, i.e.:

           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.

Body:
This might work for you (GNU sed):

sed -rn '/^\s*\w+:/!b;:a;N;/\)\s*$/!ba;/^\s*\w+:\s*SomeObj\.someFunct\s*\(/p;//d;D' file

This matches on the first variable and then appends further lines until a ) followed by possible white space and the end of a line. The pattern space is then checked to see that all other matches are met and prints the pattern space if so. Othewise the first line is deleted and the process is repeated.

N.B. As stated regexp cannot be used for matching parens in all cases, this should be left to a parser.


来源: stackexchange

问:
JavaScript: Compare dates in an array and sum the "price" for each month/year
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

```<code>transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}
</code>```

JavaScript:

```<code>request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};
</code>```

I tried to loop over the json object but I struggle to find a solution to compare the dates.

答:
I experimented a bit and came up with this solution:

var transactions = [
    {
        date: "2017-11-17",
        price: "28",
    },
    {
        date: "2017-12-17",
        price: "22",
    },
    {
        date: "2017-12-17",
        price: "20",
    }
]

var sumedUpDates = [];
var prices = [];

function isDateSumedUp(date) {
    return sumedUpDates.indexOf(date.substring(0, 7)) !== -1;
}

function sumUpDate(date) {
    var sum = 0;

    transactions.forEach(t => {
        if(t.date.substring(0, 7) === date.substring(0, 7)) {
            sum += parseInt(t.price);
        }
    });

    sumedUpDates.push(date.substring(0, 7));
    prices.push(sum);
}

transactions.forEach(t => {
    if(!isDateSumedUp(t.date)) {
        sumUpDate(t.date);
    }
});

var obj = {};

sumedUpDates.forEach((d, i) => obj[d] = prices[i]);

console.log(obj);```

ContentLicense: CC BY-SA 3.0

Body:
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

I tried to loop over the json object but I struggle to find a solution to compare the dates.


问:
Pulling .live() functionality out of jQuery
I am writing a Firefox Add-On that currently is depending on jQuery for the following things:

Selectors

Animations

A special .live("focus") hail-mary event-catching manoeuvre that happens to work with jQuery 1.4.2 (but not 1.4.4)

jQuery isn't well suited for functioning inside XUL, and it's a miracle we've gotten this far with it.  We're trying to remove the jQuery requirements, the first two are easy (animations are simple, and we can use .querySelector() instead of jQuery), but the .live has proven impossible to do on our own.  I've tried reading the source code, but I haven't been able to piece it apart.

What is the jQuery .live function doing?  There's clearly a lot more going on than document.addEventListener("focus"/"focusin",function_to_pick_apart_events).  What else is going on here?

答:
One approach might be to capture focus events at the window level, then loop through looking for elements of interest that might not already have a focus event listener and add one. An over-simplified example:

```<code><script>
function handleFocus(event) {
  event.target.value = "";
}
function captureFocus() {
  document.getElementById("target").onfocus = handleFocus;
}
window.onload = function() {
  addEventListener("focus", captureFocus, true);
}
</script>
<input id="target" value="Enter the value">
</code>```

As you can see there is no requirement for the input to exist in the document when the script executes, it will attach the event listener on the first focus event instead.

ContentLicense: CC BY-SA 4.0

Body:
One approach might be to capture focus events at the window level, then loop through looking for elements of interest that might not already have a focus event listener and add one. An over-simplified example:

<script>
function handleFocus(event) {
  event.target.value = "";
}
function captureFocus() {
  document.getElementById("target").onfocus = handleFocus;
}
window.onload = function() {
  addEventListener("focus", captureFocus, true);
}
</script>
<input id="target" value="Enter the value">

As you can see there is no requirement for the input to exist in the document when the script executes, it will attach the event listener on the first focus event instead.

ContentLicense: CC BY-SA 2.5


问:
Errors relating to date data type using Pentaho Spoon
I am reading a CSV file with information about tweets using Spoon. There is a created_at field at which time the tweet was sent.

However, the format is varied, with some examples being 'yyyy/MM/dd HH:mm', 'yyyy-MM-dd HH:mm', 'MM/dd HH:mm' and 'MM-dd', which is the reason I am getting errors.

What I would like to do is to use the date data type and still capture all the data. I thought about using the strings cut step or just changing the data type to string and increasing the length of the characters, but it may come at a cost of losing data. What else could I do?

答:
Just read them as String with no size.

According to your use case you may not have to convert them explicitly to a Date (lazy evaluation).

If you have to convert them to a Date, try a Javascript step, for which the new Date() is rather tolerant.

Otherwise you may test the format with a Regular Expression. If I take the format your give: 'yyyy/MM/dd HH:mm', 'yyyy-MM-dd HH:mm', 'MM/dd HH:mm' and 'MM-dd', this will code something like:

```<code>var created_date;
if(regex = created_at.match(/(\d\d\d\d\)\/(\d\d)\/(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(regex[1], regex[2], regex[3], regex[4], regex[5]);
if(regex = created_at.match(/(\d\d\d\d\)\-(\d\d)\-(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(regex[1], regex[2], regex[3], regex[4], regex[5]);
if(regex = created_at.match(/(\d\d)\/(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(new Date().getFullYear(), regex[1], regex[2], regex[3], regex[4]);
if(regex = created_at.match(/(\d\d)\/(\d\d))
    created_date = new Date(new Date().getFullYear(), regex[1], regex[2]);
</code>```

Then save created_data with the Date data type. Check for null values in the output flow until all the formats are defined.

Body:
Just read them as String with no size.

According to your use case you may not have to convert them explicitly to a Date (lazy evaluation).

If you have to convert them to a Date, try a Javascript step, for which the new Date() is rather tolerant.

Otherwise you may test the format with a Regular Expression. If I take the format your give: 'yyyy/MM/dd HH:mm', 'yyyy-MM-dd HH:mm', 'MM/dd HH:mm' and 'MM-dd', this will code something like:

var created_date;
if(regex = created_at.match(/(\d\d\d\d\)\/(\d\d)\/(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(regex[1], regex[2], regex[3], regex[4], regex[5]);
if(regex = created_at.match(/(\d\d\d\d\)\-(\d\d)\-(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(regex[1], regex[2], regex[3], regex[4], regex[5]);
if(regex = created_at.match(/(\d\d)\/(\d\d) (\d\d):(\d\d)/))
    created_date = new Date(new Date().getFullYear(), regex[1], regex[2], regex[3], regex[4]);
if(regex = created_at.match(/(\d\d)\/(\d\d))
    created_date = new Date(new Date().getFullYear(), regex[1], regex[2]);

Then save created_data with the Date data type. Check for null values in the output flow until all the formats are defined.


问:
TextView.setText() doesn't update text in ExpandableListView adapter
I wrote a class that extends BaseExpandableListAdapter. When a group is clicked, I want it to expand, and then my custom indicator in the view will animate a 180 rotation. And it works.

My problem is that on the same clicklistener I want to update a TextView using setText() method, but when I run it, it doesn't update the view.

I tested if the problem was in the reference to the TextView: changing the visibility, rotating it, animating it, and they all work. Its just the setText() that doesn't works.

Here is the relevant code in the adapter class: (There are actually two TextViews I would like to update)

```<code>@Override
public void onGroupExpand(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.setText(lesson.getTeacher());
    holder.classroomView.setText(lesson.getClassroom());
}

@Override
public void onGroupCollapse(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    holder.indicatorView.animate().rotation(0);
    holder.teacherView.setText("...");
    holder.classroomView.setText("");
}
</code>```

I have also tried to put this code in the getGroupView() (assign an OnClickListener to the view), but I get the same results.

Some other relevant methods:

```<code>@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}
</code>```

Any ideas why my TextView doesn't update its text?

答:
According to the answer linked by @IntelliJAmiya, The setText() doesn't update because it probably didn't run on the UI thread.

Here Is what I did to fix this issue:

```<code>@Override
public void onGroupExpand(int groupPosition) {
    final GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    final Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.post(new Runnable() {
        @Override
        public void run() {
            holder.teacherView.setText(lesson.getTeacher());
            holder.classroomView.setText(lesson.getClassroom());
        }
    });
}
</code>```

Body:
I wrote a class that extends BaseExpandableListAdapter. When a group is clicked, I want it to expand, and then my custom indicator in the view will animate a 180 rotation. And it works.

My problem is that on the same clicklistener I want to update a TextView using setText() method, but when I run it, it doesn't update the view.

I tested if the problem was in the reference to the TextView: changing the visibility, rotating it, animating it, and they all work. Its just the setText() that doesn't works.

Here is the relevant code in the adapter class: (There are actually two TextViews I would like to update)

@Override
public void onGroupExpand(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.setText(lesson.getTeacher());
    holder.classroomView.setText(lesson.getClassroom());
}

@Override
public void onGroupCollapse(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    holder.indicatorView.animate().rotation(0);
    holder.teacherView.setText("...");
    holder.classroomView.setText("");
}

I have also tried to put this code in the getGroupView() (assign an OnClickListener to the view), but I get the same results.

Some other relevant methods:

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

Any ideas why my TextView doesn't update its text?

Body:
According to the answer linked by @IntelliJAmiya, The setText() doesn't update because it probably didn't run on the UI thread.

Here Is what I did to fix this issue:

@Override
public void onGroupExpand(int groupPosition) {
    final GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    final Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.post(new Runnable() {
        @Override
        public void run() {
            holder.teacherView.setText(lesson.getTeacher());
            holder.classroomView.setText(lesson.getClassroom());
        }
    });
}


问:
Bootstrap indicators don't work on click
When slide changes indicators are in right position (1-2-3). But when I click on them, they are not responding. Prev and next links are working fine. Here is my code:

```<code><div id="theCarousel" class="carousel-slide hidden-xs" data-interval ="3000">
        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#theCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#theCarousel" data-slide-to="1"></li>
            <li data-target="#theCarousel" data-slide-to="2"></li>
        </ol>
        <div class="carousel-inner">
            <div class="item active"><img class="img-responsive" src="eberhard-grossgasteiger-311213.jpg" alt="slide 1"></div>
            <div class="item"><img class="d-block img-fluid" src="annie-spratt-176376.jpg" alt="slide 2"></div>
            <div class="item"><img class="d-block img-fluid" src="joanna-kosinska-129039.jpg" alt="slide 3"></div>
        </div><!-- /carousel-inner -->
        <!-- navigation -->
        <a class="left carousel-control" href="#theCarousel" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
        <a class="right carousel-control" href="#theCarousel" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
    </div><!-- /carousel-slide --
</code>```

Here is JS file:

```<code>// Activate Carouse
$("#theCarousel").carousel();

// Enable Carousel Indicators
$(".item").click(function(){
    $("#theCarousel").carousel(1);
 });

// Enable Carousel Control
 $(".left").click(function(){
     $("#theCarousel").carousel("prev");
 });

 $(".right").click(function(){
     $("#theCarousel").carousel("next");
 });
</code>```

What is wrong?

答:
I finally found out what went wrong. Instead of two classes:
 i wrote one with hyphen between:
.

Body: I finally found out what went wrong. Instead of two classes: <div id="myCarousel" class="carousel slide" data-ride="carousel"> i wrote one with hyphen between: <div id="theCarousel" class="carousel-slide hidden-xs" data-interval ="3000">.


问:
@ConditionalOnProperty on TYPE level w/ @Configuration
Is it possible to use @ConditionalOnProperty on TYPE level so it sees/evaluates properties defined in non-default properties files?

Following seems to work only when the property is defined in the default properties file, i.e. in application.properties

```<code>@Configuration
@ConditionalOnProperty(prefix = "jmx.rmi", value = "enabled")
public class JmxConfiguration {
    // JMX related stuff
}
</code>```

答:
@ConditionalOnProperty extracts data from org.springframework.core.env.Environment bean. It depends on you how you do populate it. You can explicitly declare multiple properties files:

```<code>@PropertySources({
        @PropertySource(name = "default", value = "classpath:application.properties"),
        @PropertySource(name = "custom", value = "file:custom.properties", ignoreResourceNotFound = true)
})
public class SpringBootApplication {...}
</code>```

And the content of both files will be appended to Environment

Body:
Is it possible to use @ConditionalOnProperty on TYPE level so it sees/evaluates properties defined in non-default properties files?

Following seems to work only when the property is defined in the default properties file, i.e. in application.properties

@Configuration
@ConditionalOnProperty(prefix = "jmx.rmi", value = "enabled")
public class JmxConfiguration {
    // JMX related stuff
}

Body:
@ConditionalOnProperty extracts data from org.springframework.core.env.Environment bean. It depends on you how you do populate it. You can explicitly declare multiple properties files:

@PropertySources({
        @PropertySource(name = "default", value = "classpath:application.properties"),
        @PropertySource(name = "custom", value = "file:custom.properties", ignoreResourceNotFound = true)
})
public class SpringBootApplication {...}

And the content of both files will be appended to Environment


问:
C# - Remove spaces in HTML source in between markups?
I am currently working on a program that allows me to enter HTML source code into a RichTextBox control and removes the spaces from in between markups.  The only problem is, I am not sure how I can differentiate between the spaces BETWEEN the markups and the spaces INSIDE the markups.  Obviously, removing the spaces inside the markups would be bad.  Any ideas as to how I can tell the difference?

Example: (before white space is removed)

```<code><p>blahblahblah</p>                  <p>blahblahblah</p>
</code>```

Example: (after white space is removed)

```<code><p>blahblahblah</p><p>blahblahblah</p>
</code>```

答:
My solution (similar to how Linarize works in the XML Tools plug-in in Notepad ++)</p>

```<code>   internal static class CONST
   {
      internal static Regex linarize_regex = new Regex(@"[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
      internal static Regex tag_linarize_regex = new Regex(@"(?<tag><[^>]*?>)[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
   }
   internal static class UTILS
   {
      internal static string linarize_html(string html)
      {
         try
            {
               html = CONST.tag_linarize_regex.Replace(html, "${tag}");
               html = CONST.linarize_regex.Replace(html, " ");
               return html;
            }
            catch (Exception)
            {
               return html;
            }
      }
   }
</code>```

Body:
I am currently working on a program that allows me to enter HTML source code into a RichTextBox control and removes the spaces from in between markups.  The only problem is, I am not sure how I can differentiate between the spaces BETWEEN the markups and the spaces INSIDE the markups.  Obviously, removing the spaces inside the markups would be bad.  Any ideas as to how I can tell the difference?

Example: (before white space is removed)

blahblahblah

blahblahblah

Example: (after white space is removed)

blahblahblah

blahblahblah

Body:
My solution (similar to how Linarize works in the XML Tools plug-in in Notepad ++)

   internal static class CONST
   {
      internal static Regex linarize_regex = new Regex(@"[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
      internal static Regex tag_linarize_regex = new Regex(@"(?<tag><[^>]*?>)[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
   }
   internal static class UTILS
   {
      internal static string linarize_html(string html)
      {
         try
            {
               html = CONST.tag_linarize_regex.Replace(html, "${tag}");
               html = CONST.linarize_regex.Replace(html, " ");
               return html;
            }
            catch (Exception)
            {
               return html;
            }
      }
   }


问:
Asp.net webform infinity scroll
I have a page shows product catalog populated by a webmethod.
When user click on image he is redirect to details page.
When user come back to catalog id like page scroll bottom at the product visited

How can i accomplish this

my html

```<code><div class="articoli">
 </div>
</code>```

my javascript

```<code><script>
$(document).ready(function () {
    var Skip = 9;
    var Take = 9;

    function Load(Skip, Take) {
        $('#divPostsLoader').html('<img src="Images/loading.gif" height="100" />');

        $.ajax({
            type: "POST",
            url: "page.aspx/LoadProduct",
            data: "{ Skip:" + Skip + ", Take:" + Take + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data != "") {
                    //accodo dati a div
                    $('.articoli').append(data.d);
                }
                $('#divPostsLoader').empty();

            },

            error: function () {
                alert('error');
            }
        })
    };

    $(window).scroll(function () {
        if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
            Load(Skip, Take);
            Skip = Skip + 9;
        }
    });
});
</code>```

my c# webmethod

```<code>[System.Web.Services.WebMethod]
public static string LoadProduct(int Skip, int Take)
{
    StringBuilder GetProduct = new StringBuilder();

    MyDataBaseEntities db = new MyDataBaseEntities();
    var prod = (from a in db.TAB
                select a).Skip(Skip).Take(Take);

    foreach (var a in prod)
    {
        var Codart = a.Codart;
        var Prezz = a.Prezz;
        var pathimg = a.pathimg;

        GetProduct.Append("<div class=\"col-md-4\">");
        GetProduct.Append("<div class=\"col-md-6 text-left\">");
        GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
        GetProduct.AppendFormat("<span class=\"codart\">{0}</span>", Codart);
        GetProduct.Append("</a>");
        GetProduct.Append("</div> ");
        GetProduct.Append("<div class=\"col-md-6 text-right\" style=\"color:gray;font-size:large;\">");
        GetProduct.AppendFormat(string.Format("{0:c}",  Prezz));
        GetProduct.Append("</div> ");
        GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
        GetProduct.AppendFormat(string.Format("<img src='{0}' class='img-responsive MyImage' alt='{1}'/>", pathimg, Codart));
        GetProduct.Append("</a>");
        GetProduct.Append("</div> ");
    }
    return GetProduct.ToString();
}
</code>```

how can i scroll bottom at page load?

答:
use this and set the variable sc</p>

```<code>var sc;
var scroll;
var loop = setInterval(function() {
sc = window.scrollTop;
if (scroll === null) {
localstorage.setItem("bgc", sc);
}
}, 10);
window.onload = function() {
scroll = localstorage.getItem("bgc");
 if (scroll !== null) {
 window.scollTop = scroll + "px";
 }
 }
</code>```

Title: Asp.net webform infinity scroll

Body:
I have a page shows product catalog populated by a webmethod.
When user click on image he is redirect to details page.
When user come back to catalog id like page scroll bottom at the product visited

How can i accomplish this

my html

my javascript

Body:
use this and set the variable sc

var sc;
var scroll;
var loop = setInterval(function() {
sc = window.scrollTop;
if (scroll === null) {
localstorage.setItem("bgc", sc);
}
}, 10);
window.onload = function() {
scroll = localstorage.getItem("bgc");
 if (scroll !== null) {
 window.scollTop = scroll + "px";
 }
 }


问:
C++ concepts and template specialization; how to get a user-friendly compiler error
I have two (or more) templates that can each adapt a specific set of classes, identified by a concept. To make it possible for the two templates to have the same name, they must be specializations.

```<code>template< typename T >
struct pin_in { static_assert( always_false<T>::value, . . . ); };

template< is_pin_in T >
struct pin_in< T > . . .

template< is_pin_in_out T >
struct pin_in< T > . . .
</code>```

This works OK when one of the specializations match. When none match the base template is selected, and I get the assertion failure. The mechanism works. I love concepts!

But the error message I get (GCC 7.2.0) points to the assertion. Can I somehow make the base template not be selected, so I would get an error message that tells that no template matched the argument class?

答:
Hurray, I found a solution! What you need is to have the main template constrained:

```<code>template <class T>
    requires is_pin_in<T> || is_pin_in_out<T>
struct pin_in {};

template <is_pin_in T>
struct pin_in<T> {};

template <is_pin_in_out T>
struct pin_in<T> {};
</code>```

And you get a good diagnostic message:

```<code><source>: In function 'auto test()':
29 : <source>:29:16: error: template constraint failure
     pin_in<char> a;
                ^
29 : <source>:29:16: note:   constraints not satisfied
7 : <source>:7:24: note: within 'template<class T> concept const bool is_pin_in<T> [with T = char]'
 constexpr concept bool is_pin_in = std::is_same_v<T, int>;
                        ^~~~~~~~~
7 : <source>:7:24: note: 'std::is_same_v' evaluated to false
9 : <source>:9:24: note: within 'template<class T> concept const bool is_pin_in_out<T> [with T = char]'
 constexpr concept bool is_pin_in_out = std::is_same_v<T, unsigned>;
                        ^~~~~~~~~~~~~
9 : <source>:9:24: note: 'std::is_same_v' evaluated to false
Compiler exited with result code 1
</code>```

well, my message is with some dummy constraints, but you get the point

Body:
I have two (or more) templates that can each adapt a specific set of classes, identified by a concept. To make it possible for the two templates to have the same name, they must be specializations.

template< typename T >
struct pin_in { static_assert( always_false<T>::value, . . . ); };

template< is_pin_in T >
struct pin_in< T > . . .

template< is_pin_in_out T >
struct pin_in< T > . . .

This works OK when one of the specializations match. When none match the base template is selected, and I get the assertion failure. The mechanism works. I love concepts!

But the error message I get (GCC 7.2.0) points to the assertion. Can I somehow make the base template not be selected, so I would get an error message that tells that no template matched the argument class?

Body:
Hurray, I found a solution! What you need is to have the main template constrained:

template <class T>
    requires is_pin_in<T> || is_pin_in_out<T>
struct pin_in {};

template <is_pin_in T>
struct pin_in<T> {};

template <is_pin_in_out T>
struct pin_in<T> {};

And you get a good diagnostic message:

<source>: In function 'auto test()':
29 : <source>:29:16: error: template constraint failure
     pin_in<char> a;
                ^
29 : <source>:29:16: note:   constraints not satisfied
7 : <source>:7:24: note: within 'template<class T> concept const bool is_pin_in<T> [with T = char]'
 constexpr concept bool is_pin_in = std::is_same_v<T, int>;
                        ^~~~~~~~~
7 : <source>:7:24: note: 'std::is_same_v' evaluated to false
9 : <source>:9:24: note: within 'template<class T> concept const bool is_pin_in_out<T> [with T = char]'
 constexpr concept bool is_pin_in_out = std::is_same_v<T, unsigned>;
                        ^~~~~~~~~~~~~
9 : <source>:9:24: note: 'std::is_same_v' evaluated to false
Compiler exited with result code 1

well, my message is with some dummy constraints, but you get the point


问:
how can print big string from a string array or get its index
I want to do a function that takes array of strings and print the big string and the num of chars, for example

```<code>String[] names = { "Microsoft", "lg", "apple","Samsung"}
</code>```

the output is:

bigger name is :Microsoft

num of chars 9

I have done num of chars but i don't know how to print the name**

```<code>String[] names = { "microsoft", "lg", "apple","samsung"};
int big = 0;
for (int i = 0; i < names.Length; i++) {
    if (big<names[i].Length) {
        big = names[i].Length;
    }
}
Console.WriteLine("bigger name is{0}chars  ",big);

</code>```

答:
Using Linq:

```<code>String[] names = { "microsoft", "lg", "apple", "samsung" };

string longestName = names.OrderByDescending(n => n.Length).FirstOrDefault();

if (!String.IsNullOrEmpty(longestName))
{
    Console.WriteLine("Longest name is {0} ({1} chars).", longestName, longestName.Length);
}

Console.ReadLine();
</code>```

There is also a more efficient way, see Is there a LINQ function for getting the longest string in a list of strings?

Body:
I want to do a function that takes array of strings and print the big string and the num of chars, for example

String[] names = { "Microsoft", "lg", "apple","Samsung"}

the output is:

bigger name is :Microsoft

num of chars 9

I have done num of chars but i don't know how to print the name**

String[] names = { "microsoft", "lg", "apple","samsung"};
int big = 0;
for (int i = 0; i < names.Length; i++) {
    if (big<names[i].Length) {
        big = names[i].Length;
    }
}
Console.WriteLine("bigger name is{0}chars  ",big);

Body:
Using Linq:

String[] names = { "microsoft", "lg", "apple", "samsung" };

string longestName = names.OrderByDescending(n => n.Length).FirstOrDefault();

if (!String.IsNullOrEmpty(longestName))
{
    Console.WriteLine("Longest name is {0} ({1} chars).", longestName, longestName.Length);
}

Console.ReadLine();

There is also a more efficient way, see Is there a LINQ function for getting the longest string in a list of strings?


问:
How to make Azure AD autorization flow from SPA to Spring Boot Rest service
We have a SPA that is protected with Azure AD. This seems to work fine, and users can authenticate ok.

We also have a spring boot rest service, that is also secured by Azure AD. When we try to do an GET from e.g. chrome, we get redirected to Azure for authentication, and then routed back to the rest service where we get the result.

But, when we try to call this rest service from SPA client, it does not work. Our client is running on http://localhost:5010/ and when we try to access the rest service, after the client itself successfully has authenticated against Azure, we just get a redirect to http://localhost:5010/login

This tells me that the rest service are not able to verify the clients authenication, but I don't understand why.

We use adal-angular4 in our SPA and adal4j in our spring boot server.

How can I make the rest service accept tokens from SPA client, without trying to re-authenticate rest service?

答:
According to the comment, you got these as headers:

```<code>Host: localhost:5010
Connection: keep-alive
Accept: application/json, text/plain, /
X-XSRF-TOKEN: 1c35cf04-25a1-4c59-8429-6e48b8484ef3
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Referer: localhost:5010/vesselActivity
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,nb;q=0.8
Cookie: XSRF-TOKEN=1c35cf04-25a1-4c59-8429-6e48b8484ef3
</code>```

Only Cookie is XSRF cookie, so it seems you're lacking authorization headers in your client app.

Body:
According to the comment, you got these as headers:

Host: localhost:5010
Connection: keep-alive
Accept: application/json, text/plain, /
X-XSRF-TOKEN: 1c35cf04-25a1-4c59-8429-6e48b8484ef3
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Referer: localhost:5010/vesselActivity
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,nb;q=0.8
Cookie: XSRF-TOKEN=1c35cf04-25a1-4c59-8429-6e48b8484ef3

Only Cookie is XSRF cookie, so it seems you're lacking authorization headers in your client app.


问:
Force HTTPS/SSL for all controller/request specs in rspec
I'm using RSpec 3.5.0, and would like to enable HTTPS/SSL requests for all my specs.

Since I added force_ssl to my ApplicationController, all my specs are failing, since they are redirecting to the secure version of the site instead of rendering, etc.

答: The suggestions here don't work under rails 5.  If that's part of where you're stuck adding https! to your spec should work.


问:
Issue using Terraform EC2 Userdata
I am deploying a bunch of EC2 instances that require a mount called /data, this is a seperate disk that I am attaching using volume attach in AWS.

Now when I did the following manually it works fine, so the script I use works however when adding it via userdata I am seeing issues and the mkfs command is not happening.

If you see my terraform config:

```<code>resource "aws_instance" "riak" {
  count = 5
  ami = "${var.aws_ami}"
  vpc_security_group_ids = ["${aws_security_group.bastion01_sg.id}","${aws_security_group.riak_sg.id}","${aws_security_group.outbound_access_sg.id}"]
  subnet_id = "${element(module.vpc.database_subnets, 0)}"
  instance_type = "m4.xlarge"
  tags {
    Name = "x_riak_${count.index}"
    Role = "riak"
  }
  root_block_device {
    volume_size = 20
  }
  user_data = "${file("datapartition.sh")}"
}

resource "aws_volume_attachment" "riak_data" {
  count = 5
  device_name = "/dev/sdh"
  volume_id  = "${element(aws_ebs_volume.riak_data.*.id, count.index)}"
  instance_id = "${element(aws_instance.riak.*.id, count.index)}"
}
</code>```

And then the partition script is as follows:

```<code>#!/bin/bash

if [ ! -d /data ];
then mkdir /data
fi

/sbin/mkfs -t ext4 /dev/xvdh;

while [ -e /dev/xvdh ] ; do sleep 1 ; done

mount /dev/xvdh /data

echo "/dev/xvdh /data ext4 defaults 0 2" >> /etc/fstab
</code>```

Now when I do this via terraform the mkfs doesn't appear to happen and I see no obvious errors in the syslog. If I copy the script manually and just bash script.sh the mount is created and works as expected.

Has anyone got any suggestions here?

Edit: It's wort noting adding this in AWS gui under userdata also works fine.

答:
You could try with remote_exec instead of user_data.

User_data relates on cloud-init which can act differently depending on images of your cloud provider.

And also i'm not sure it's a good idea to exec a script that would wait for some time before executing in the cloud-init section => this may lead to VM considering launch has failed because of a timeout (depending on your cloud provider).

Remote_exec may be better here because you will be able to wait until your /dev/xvdh is attached

See here

```<code>resource "aws_instance" "web" {
  # ...

  provisioner "file" {
    source      = "script.sh"
    destination = "/tmp/script.sh"
  }

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/script.sh",
      "/tmp/script.sh args",
    ]
  }
}
</code>```

Title: Issue using Terraform EC2 Userdata

Body:
I am deploying a bunch of EC2 instances that require a mount called /data, this is a seperate disk that I am attaching using volume attach in AWS.

Now when I did the following manually it works fine, so the script I use works however when adding it via userdata I am seeing issues and the mkfs command is not happening.

If you see my terraform config:

resource "aws_instance" "riak" {
  count = 5
  ami = "${var.aws_ami}"
  vpc_security_group_ids = ["${aws_security_group.bastion01_sg.id}","${aws_security_group.riak_sg.id}","${aws_security_group.outbound_access_sg.id}"]
  subnet_id = "${element(module.vpc.database_subnets, 0)}"
  instance_type = "m4.xlarge"
  tags {
    Name = "x_riak_${count.index}"
    Role = "riak"
  }
  root_block_device {
    volume_size = 20
  }
  user_data = "${file("datapartition.sh")}"
}

resource "aws_volume_attachment" "riak_data" {
  count = 5
  device_name = "/dev/sdh"
  volume_id  = "${element(aws_ebs_volume.riak_data.*.id, count.index)}"
  instance_id = "${element(aws_instance.riak.*.id, count.index)}"
}

And then the partition script is as follows:

#!/bin/bash

if [ ! -d /data ];
then mkdir /data
fi

/sbin/mkfs -t ext4 /dev/xvdh;

while [ -e /dev/xvdh ] ; do sleep 1 ; done

mount /dev/xvdh /data

echo "/dev/xvdh /data ext4 defaults 0 2" >> /etc/fstab

Now when I do this via terraform the mkfs doesn't appear to happen and I see no obvious errors in the syslog. If I copy the script manually and just bash script.sh the mount is created and works as expected.

Has anyone got any suggestions here?

Edit: It's wort noting adding this in AWS gui under userdata also works fine.

Body:
You could try with remote_exec instead of user_data.

User_data relates on cloud-init which can act differently depending on images of your cloud provider.

And also i'm not sure it's a good idea to exec a script that would wait for some time before executing in the cloud-init section => this may lead to VM considering launch has failed because of a timeout (depending on your cloud provider).

Remote_exec may be better here because you will be able to wait until your /dev/xvdh is attached

See here

resource "aws_instance" "web" {
  # ...

  provisioner "file" {
    source      = "script.sh"
    destination = "/tmp/script.sh"
  }

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/script.sh",
      "/tmp/script.sh args",
    ]
  }
}


问:
How to scrape data from justdial.com?
I want to fetch all the phone numbers and the names of the doctors from the mentioned website. I'm currently facing some issues about scraping the data. I've downloaded the html page for scraping but showing me errors The error is

Warning:
file_get_contents(file:///C:/Program%20Files%20(x86)/xampp/htdocs/scrape_demo/Top%20Ayurvedic%20Doctors%20in%20kolkata.html):
failed to open stream: No such file or directory in C:\Program Files
(x86)\xampp\htdocs\scrape_demo\simple_html_dom.php on line 75

Fatal error: Call to a member function find() on a non-object in
C:\Program Files (x86)\xampp\htdocs\scrape_demo\scrape_justdial.php on
line 4

And here is my code -

```<code><?php
    include_once('simple_html_dom.php');
    $html = file_get_html('file:///C:/Program%20Files%20(x86)/xampp/htdocs/scrape_demo/Top%20Ayurvedic%20Doctors%20in%20kolkata.html');
    foreach($html->find('div.col-sm-5 col-xs-8 store-details sp-detail paddingR0') as $element){
    echo $element->innertext . '<br/>';
}
?>
</code>```

I'm waiting for the solution

答: file_get_content does not know about the file protocol. Just use it with a proper path like C:/Program%20Files%20(x86)/xampp/htdocs/scrape_demo/Top%20Ayurvedic%20Doctors%20in%20kolkata.html

Title: How to scrape data from justdial.com?

Body:
I want to fetch all the phone numbers and the names of the doctors from the mentioned website. I'm currently facing some issues about scraping the data. I've downloaded the html page for scraping but showing me errors The error is

Warning:
file_get_contents(file:///C:/Program%20Files%20(x86)/xampp/htdocs/scrape_demo/Top%20Ayurvedic%20Doctors%20in%20kolkata.html):
failed to open stream: No such file or directory in C:\Program Files
(x86)\xampp\htdocs\scrape_demo\simple_html_dom.php on line 75

Fatal error: Call to a member function find() on a non-object in
C:\Program Files (x86)\xampp\htdocs\scrape_demo\scrape_justdial.php on
line 4

And here is my code -

<?php
    include_once('simple_html_dom.php');
    $html = file_get_html('file:///C:/Program%20Files%20(x86)/xampp/htdocs/scrape_demo/Top%20Ayurvedic%20Doctors%20in%20kolkata.html');
    foreach($html->find('div.col-sm-5 col-xs-8 store-details sp-detail paddingR0') as $element){
    echo $element->innertext . '
';
}
?>

I'm waiting for the solution


问:
Switch Teradata Accounts
I want to be able to switch between 2 Teradata accounts if the password has expired for one user in SAS.
e.g. connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

terauser : Password expired
terauser1 : Password valid

Couple of questions:

How do I pre-warn the user to change password. Do I use the DBC.Users table.

How do I swicth accounts, as I will know the status only in the logs.

答:
Proc SQL maintains some automatic macro variables that you can examine:

```<code>Proc SQL;
  connect to ....;

  %put NOTE: SQLXRC=%superq(SQLXRC);
  %put NOTE: SQLXMSG=%superq(SQLXMSG);
</code>```

If you want to automatically test and use the working account you could create a macro that performs try connection and switch account behavior.  Be careful about security policies if you put user account info in source code or a plain-text file.

Example:

```<code>%macro myConnect ();
  %* To be used in the context of a Proc SQL statement;

  %* ... assign first account connection parameters to  macro variables;
  %let terauser=...;
  ...
  %let tdserver = ...;

  connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

  %if &SQLXRC eq 0 %then %return;

  %* ... assign second account connection parameters to  macro variables;
  %let terauser=...;
  ...
  %let tdserver = ...;

  connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

  %if &SQLXRC eq 0 %then %return;

  %put ERROR: Could not connect with current connection parameters;
  %abort cancel;
%mend;
</code>```

Proc SQL can also connect using existing remote library references:

```<code>* create remote library references;
libname account1 Teradata ... connection parameters ...;
libname account2 Teradata ... connection parameters ...;

Proc SQL;
  connect using account1;  * connect using the account1
</code>```

Title: Switch Teradata Accounts

Body:
Proc SQL maintains some automatic macro variables that you can examine:

Proc SQL;
  connect to ....;

  %put NOTE: SQLXRC=%superq(SQLXRC);
  %put NOTE: SQLXMSG=%superq(SQLXMSG);

If you want to automatically test and use the working account you could create a macro that performs try connection and switch account behavior.  Be careful about security policies if you put user account info in source code or a plain-text file.

Example:

%macro myConnect ();
  %* To be used in the context of a Proc SQL statement;

  %* ... assign first account connection parameters to  macro variables;
  %let terauser=...;
  ...
  %let tdserver = ...;

  connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

  %if &SQLXRC eq 0 %then %return;

  %* ... assign second account connection parameters to  macro variables;
  %let terauser=...;
  ...
  %let tdserver = ...;

  connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

  %if &SQLXRC eq 0 %then %return;

  %put ERROR: Could not connect with current connection parameters;
  %abort cancel;
%mend;

Proc SQL can also connect using existing remote library references:

* create remote library references;
libname account1 Teradata ... connection parameters ...;
libname account2 Teradata ... connection parameters ...;

Proc SQL;
  connect using account1;  * connect using the account1


问:
Not able to click on second row of datepicker while adding data in jquery
I am generating rows on click of .add class. SO when I generate 3 rows, and I start adding data for the first row in datepicker. It gives me to add the date.

But when I go and set date for second row, the mouse takes me to the first fromdate text control.

same thing is happening for todate also. Even I generate different ID;s for each row still i am unable to add the date for second and third row.

Below is my html

```<code><tr>
                            <td>
                                <div class="row noPadding vendorForm">
                                    <div class="vendorDaterow">
                                        <div class="vendorName" id="dvVendorNameData">
                                            <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate1" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate1" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    <div class="add">
                                        <i class="fa fa-plus" aria-hidden="true"></i>
                                    </div>
                                    <i class="max">(Maximum 5 Vendors)</i>
                                </div>
                            </td>
                        </tr>
</code>```

Here is my fiddle for generated HTML

Kindly suggest where I am wrong and I am unable to add date for second and third row

答:
Check this Code it will working datepicker for cloned element,hasDatepicker class remove for datepicker input after adding clone element to tr and apply  $('.dateClass').datepicker({ dateFormat: "m/d/yy" }); so datepicker working properly

$('.dateClass').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: "m/d/yy"
});
    $(document).ready(function () {
    var toAddCloneCount = 2;

    $('.add').on('click', function () {
        var $tr = $(this).closest('tr');
        var $tr2 = $tr.clone(true, true);
        $tr2.find(".vendorName").children('label').remove();
        $tr2.find(".add").children().remove();
        $tr2.find(".vendorFromDate").children('label').remove();
        $tr2.find(".vendorToDate").children('label').remove();
        $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
        $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
        $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);

        $tr2.insertAfter($tr);
         $('.dateClass').removeClass('hasDatepicker').datepicker();
    });
       });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ui-datepicker-div { font-size: 12px; } </code>```

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

                                                SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName">

                                                From Date<input type="text" name="spFromDate1" id="spFromDate1" class="dateClass ">

                                                To Date<input type="text" name="spToDate" id="spToDate1" class="dateClass ">

                                        (Maximum 5 Vendors)

```

Body:
I am generating rows on click of .add class. SO when I generate 3 rows, and I start adding data for the first row in datepicker. It gives me to add the date.

But when I go and set date for second row, the mouse takes me to the first fromdate text control.

same thing is happening for todate also. Even I generate different ID;s for each row still i am unable to add the date for second and third row.

Below is my html

                                            SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName" />

                                            From Date<input type="text" name="spFromDate" id="spFromDate1" class="dateClass" />

                                            To Date<input type="text" name="spToDate" id="spToDate1" class="dateClass" />

                                    (Maximum 5 Vendors)

Here is my fiddle for generated HTML

Kindly suggest where I am wrong and I am unable to add date for second and third row

Body:
Check this Code it will working datepicker for cloned element,hasDatepicker class remove for datepicker input after adding clone element to tr and apply  $('.dateClass').datepicker({ dateFormat: "m/d/yy" }); so datepicker working properly

$('.dateClass').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: "m/d/yy"
});
    $(document).ready(function () {
    var toAddCloneCount = 2;

    $('.add').on('click', function () {
        var $tr = $(this).closest('tr');
        var $tr2 = $tr.clone(true, true);
        $tr2.find(".vendorName").children('label').remove();
        $tr2.find(".add").children().remove();
        $tr2.find(".vendorFromDate").children('label').remove();
        $tr2.find(".vendorToDate").children('label').remove();
        $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
        $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
        $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);

        $tr2.insertAfter($tr);
         $('.dateClass').removeClass('hasDatepicker').datepicker();
    });
       });

#ui-datepicker-div { font-size: 12px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<table>
<tr>
                                <td>
                                    <div class="row noPadding vendorForm">
                                        <div class="vendorDaterow">
                                            <div class="vendorName" id="dvVendorNameData">
                                                <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName"></span>
                                            </div>
                                            <div class="vendorFromDate">
                                                <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate1" id="spFromDate1" class="dateClass "><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                            </div>
                                            <div class="vendorToDate">
                                                <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate1" class="dateClass "><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                            </div>
                                        </div>
                                        <div class="add">
                                            <i class="fa fa-plus" aria-hidden="true"></i>
                                        </div>
                                        <i class="max">(Maximum 5 Vendors)</i>

                                    </div>
                                </td>
                            </tr>
</table>


问:
How do pagerank checking services work?
How do pagerank checking services work?</p>

答: Most services just copy what the Google tool bar shows. But pagerank is usually not the important thing, the important thing is to get quality backlinks with relevant anchor text.</p>

Title: How do pagerank checking services work?

Body: How do pagerank checking services work?


问:
Can't test successfully for view that puts form data in session
I'm trying to test a view that stores validated form data in the session. However when I try to test this I get back None for the session value and the error:

AssertionError: 'example_postcode' != None

The test is:

```<code>class TestSignup(TestCase):

    def test_postcode(self):
        postcode = 'example_postcode'
        self.client.post('/users/postcode/',  {'postcode': postcode})
        self.assertEqual(postcode, self.client.session.get('postcode'))
</code>```

the view is:

```<code>@require_http_methods(['GET', 'HEAD', 'POST'])
def postcode_view(request,):
    if request.method == 'POST':
        form = PostcodeForm(request.POST)
        if form.is_valid():
            request.session.update(form.cleaned_data)
            return redirect('users:signup_2')
    else:
        form = form_class()
    context.update({'form': form})
    return render(request, 'pages/signup_postcode.html', context)
</code>```

form

```<code>class PostcodeForm(forms.Form):
    postcode = GBPostcodeField(label='Please enter your postcode',
                               error_messages={'invalid': 'Please enter a valid postcode'})
</code>```

答: The comments above by others confirmed the test was largely correct and the error was a trailing slash which is now updated above.  </p>

Body:
I'm trying to test a view that stores validated form data in the session. However when I try to test this I get back None for the session value and the error:

AssertionError: 'example_postcode' != None

The test is:

class TestSignup(TestCase):

    def test_postcode(self):
        postcode = 'example_postcode'
        self.client.post('/users/postcode/',  {'postcode': postcode})
        self.assertEqual(postcode, self.client.session.get('postcode'))

the view is:

@require_http_methods(['GET', 'HEAD', 'POST'])
def postcode_view(request,):
    if request.method == 'POST':
        form = PostcodeForm(request.POST)
        if form.is_valid():
            request.session.update(form.cleaned_data)
            return redirect('users:signup_2')
    else:
        form = form_class()
    context.update({'form': form})
    return render(request, 'pages/signup_postcode.html', context)

form

class PostcodeForm(forms.Form):
    postcode = GBPostcodeField(label='Please enter your postcode',
                               error_messages={'invalid': 'Please enter a valid postcode'})


问:
Iterate through string.find in Lua
Currently I work on a project within the game Minecraft and OpenComputers. The main coding language is Lua.

Now, I need to find a nice solution to iterate through a string.

My current solution looks like this:

```<code>local config = "key1=type1\nkey2=type2\nkey3=type3"
local lines = {}
while true do
    local length = config:len()
    local s, f = config:find("\n")
    if s ~= nil then
        table.insert(lines, config:sub(1, s-1))
        config = config:sub(f+1, length)
    else
        table.insert(lines, config)
        break
    end
end
</code>```

In this example I have a static string in the variable config but in the real code I read the lines from a config file.

My solution works, but I think it can be cleaner. Is there a cleaner solution?

答:
If you want to iterate over the lines in a file, use io.lines:

```<code>local lines = {}
for l in io.lines("config.txt") do
    table.insert(lines, l)
end
</code>```

Title: Iterate through string.find in Lua

Body:
Currently I work on a project within the game Minecraft and OpenComputers. The main coding language is Lua.

Now, I need to find a nice solution to iterate through a string.

My current solution looks like this:

local config = "key1=type1\nkey2=type2\nkey3=type3"
local lines = {}
while true do
    local length = config:len()
    local s, f = config:find("\n")
    if s ~= nil then
        table.insert(lines, config:sub(1, s-1))
        config = config:sub(f+1, length)
    else
        table.insert(lines, config)
        break
    end
end

In this example I have a static string in the variable config but in the real code I read the lines from a config file.

My solution works, but I think it can be cleaner. Is there a cleaner solution?

Body:
If you want to iterate over the lines in a file, use io.lines:

local lines = {}
for l in io.lines("config.txt") do
    table.insert(lines, l)
end


问:
Get the Value of Year from a DateTime Column in Azure U-SQL?
I am using U-SQL script to get the Datetime column data from the Azure DataLake Analytics Table. I am having a date of joining datetime column in a employee table, I want display only the year of joining from that column. There may be a chance of getting null value from the table.

joineddate.HasValue ? joineddate.Value.Year.ToString() : joineddate AS JoinedDate

The above statement shows a error,

```<code>Cannot implicitly convert type 'string' to 'System.DateTime'
</code>```

Please Suggest me a way to do this thing.

Thanks in Advance!

答:
I have used ToString to the datetime column and got the desired output.

```<code>string.IsNullOrEmpty(joineddate.ToString()) ? joineddate.ToString() : joineddate.Value.Year.ToString() AS JoinedDate
</code>```

Thanks.

Body:
I am using U-SQL script to get the Datetime column data from the Azure DataLake Analytics Table. I am having a date of joining datetime column in a employee table, I want display only the year of joining from that column. There may be a chance of getting null value from the table.

joineddate.HasValue ? joineddate.Value.Year.ToString() : joineddate AS JoinedDate

The above statement shows a error,

Cannot implicitly convert type 'string' to 'System.DateTime'

Please Suggest me a way to do this thing.

Thanks in Advance!

Body:
I have used ToString to the datetime column and got the desired output.

string.IsNullOrEmpty(joineddate.ToString()) ? joineddate.ToString() : joineddate.Value.Year.ToString() AS JoinedDate

Thanks.


问:
filtering in an ng-repeat from JSON response
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

```<code>$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});
</code>```

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow" ng-repeat="customer in customers | orderBy: customer.id">
        <div class="col-lg-8">
            <p class="customer" ng-bind="customer.id + ' ' + customer.firstname + ' ' + customer.lastname">
      </p>
        </div>
</div></code>```

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

```<code>{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}
</code>```

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <ng-form name="stock">
                <div ng-repeat="stock_available in stock_availables">
                    <div class="row full-width padding-tb-15" ng-if="stock_available.id_product == product.id  && stock_available.id_product_attribute == 0" ng-repeat="product in products">
                        <div class="col-lg-12 form-stock-group hidden">
                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">
                        </div>
                        <div class="col-lg-4">
                            <h5 ng-bind="product.name.language"></h5>
                        </div>
                        <div class="col-lg-3">
                            <h5 ng-bind="product.ean13"></h5>
                        </div>
                        <div class="col-lg-2">
                            <h5 ng-bind="product.reference"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">
                            <h5 title="quantity" name="stockQuantity" aria-describedby="" ng-model="stock_available.quantity" ng-bind="stock_available.quantity"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">
                        </div>
                        <div class="col-lg-1 text-center">

                                <i class="fa fa-print" aria-hidden="true"></i>

                        </div>
                    </div>
                </div>
            </ng-form>
        </div>
    </div></code>```

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

答:
I think it's better for you to let DB order it for you.
But you can try AngularJS orderBy or filter

var module = angular.module('MyApp', []);

module.controller('MyController', function($scope){

  $scope.list = [
  { 'id': 0, 'count': 10 },
  { 'id': 1, 'count': 9 },
  { 'id': 2, 'count': 8 }];

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

<div ng-app="MyApp">
  <div ng-controller="MyController">

    <div ng-repeat="member in list | orderBy:'-count'">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | filter: {id:0}">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | orderBy: '-count' | filter: {id : '!0'}">
      {{member.id}}
    </div>
  </div>
</div></code>```

Body:
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});

            <ng-form name="stock">

                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">

                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">

                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">

            </ng-form>

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

Body:
I think it's better for you to let DB order it for you.
But you can try AngularJS orderBy or filter

var module = angular.module('MyApp', []);

module.controller('MyController', function($scope){

  $scope.list = [
  { 'id': 0, 'count': 10 },
  { 'id': 1, 'count': 9 },
  { 'id': 2, 'count': 8 }];

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
  <div ng-controller="MyController">

    <div ng-repeat="member in list | orderBy:'-count'">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | filter: {id:0}">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | orderBy: '-count' | filter: {id : '!0'}">
      {{member.id}}
    </div>
  </div>
</div>


问:
Magento custom module date field saving date to one day before the selected date
i followed steps on this link to add a date field to my custom module :

http://magentomechanic.blogspot.com/2010/01/to-add-custom-date-field-in-custom.html

Everything went fine, except for the that when i select a date and save configurations, it returns me date one day before the selected one :(

For Example :

When i select 25 Feb, 2012 and save , it will save and return 24 Feb, 2012.

Notice it saved one day before :(

i get this when i print_r($model) in admin controller before save:

```<code>[start_date] => 2012-01-24 16:00:00 // i set it to 25 but its saving 24
[end_date] => 2012-01-26 16:00:00  // i set it to 27 but .....
[status] => 1 [content] => asdasdadsd
[created_time] => 2012-01-25 07:27:11 // it gives current date and it is O'rite
[update_time] => 2012-01-25 07:27:11 ) //it gives current date and it is O'rite
</code>```

NOTE:

i echo the posted date and it was right what i set to mean there is no problem with the post data,
mean client side is clear for any bug, so where the problem lies is when it is converted to save in database !!! Any help ???

Here is my initiall code i tried :

```<code>if($data['start_date'] != NULL )
                {
                $date = Mage::app()->getLocale()->date($data['start_date'], Zend_Date::DATE_SHORT);
                $model->setStartDate($date->toString('YYYY-MM-dd HH:mm:ss'));
                }
                if($data['end_date'] != NULL)
                {
                $date1 = Mage::app()->getLocale()->date($data['end_date'], Zend_Date::DATE_SHORT);
                $model->setEndDate($date1->toString('YYYY-MM-dd HH:mm:ss'));
                }
</code>```

then i tried this one :

```<code>echo $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT).'<br/>';
                if($data['start_date'] != NULL )
                {
                    echo $data['start_date']."<br/>"; // 01/27/12 correct date posted which i entered
                    $date = Mage::app()->getLocale()->date($data['start_date'], $format);
                    echo $date; /// Jan 26, 2012 4:00:00 PM but here we get back to one day
                    $time = $date->getTimestamp();
                    $model->setStartDate(Mage::getSingleton('core/date')->date(null, $time));

                    //$model->setStartDate($date->toString('YYYY-MM-dd HH:mm:ss'));
                }
                if($data['end_date'] != NULL)
                {
                    echo $data['end_date'].'<br/>';
                    $date1 = Mage::app()->getLocale()->date($data['end_date'], $format);

                    $time = $date1->getTimestamp();
                    $model->setEndDate(Mage::getSingleton('core/date')->date(null, $time));

                    //$model->setEndDate($date1->toString('YYYY-MM-dd HH:mm:ss'));
                }
</code>```

$format echoes : M/d/yy
original posted date : 01/27/12
$date echo result :Jan 26, 2012 4:00:00 PM

答:
```<code>$preSaleDate = $_product->getAvailabilityDate();//product attribute

if($preSaleDate) {
  $format = 'Y-m-d H:i:s'; //current format
  $formatted_date = DateTime::createFromFormat($format, $preSaleDate)->format('m/d/Y');
  $dateReal = Mage::app()->getLocale()->date($formatted_date
                                                  ,Zend_Date::DATE_SHORT, null, false);
  $format = 'long'; // short, long, medium, full
  $dueDate = Mage::helper('core')->formatDate($dateReal, $format, false);

  echo $dueDate;// will get same day as original $preSaleDate
}
</code>```

Body:
i followed steps on this link to add a date field to my custom module :

http://magentomechanic.blogspot.com/2010/01/to-add-custom-date-field-in-custom.html

Everything went fine, except for the that when i select a date and save configurations, it returns me date one day before the selected one :(

For Example :

When i select 25 Feb, 2012 and save , it will save and return 24 Feb, 2012.

Notice it saved one day before :(

i get this when i print_r($model) in admin controller before save:

[start_date] => 2012-01-24 16:00:00 // i set it to 25 but its saving 24
[end_date] => 2012-01-26 16:00:00  // i set it to 27 but .....
[status] => 1 [content] => asdasdadsd
[created_time] => 2012-01-25 07:27:11 // it gives current date and it is O'rite
[update_time] => 2012-01-25 07:27:11 ) //it gives current date and it is O'rite

NOTE:

i echo the posted date and it was right what i set to mean there is no problem with the post data,
mean client side is clear for any bug, so where the problem lies is when it is converted to save in database !!! Any help ???

Here is my initiall code i tried :

if($data['start_date'] != NULL )
                {
                $date = Mage::app()->getLocale()->date($data['start_date'], Zend_Date::DATE_SHORT);
                $model->setStartDate($date->toString('YYYY-MM-dd HH:mm:ss'));
                }
                if($data['end_date'] != NULL)
                {
                $date1 = Mage::app()->getLocale()->date($data['end_date'], Zend_Date::DATE_SHORT);
                $model->setEndDate($date1->toString('YYYY-MM-dd HH:mm:ss'));
                }

then i tried this one :

echo $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT).'
';
                if($data['start_date'] != NULL )
                {
                    echo $data['start_date']."
"; // 01/27/12 correct date posted which i entered
                    $date = Mage::app()->getLocale()->date($data['start_date'], $format);
                    echo $date; /// Jan 26, 2012 4:00:00 PM but here we get back to one day
                    $time = $date->getTimestamp();
                    $model->setStartDate(Mage::getSingleton('core/date')->date(null, $time));

                    //$model->setStartDate($date->toString('YYYY-MM-dd HH:mm:ss'));
                }
                if($data['end_date'] != NULL)
                {
                    echo $data['end_date'].'
';
                    $date1 = Mage::app()->getLocale()->date($data['end_date'], $format);

                    $time = $date1->getTimestamp();
                    $model->setEndDate(Mage::getSingleton('core/date')->date(null, $time));

                    //$model->setEndDate($date1->toString('YYYY-MM-dd HH:mm:ss'));
                }

$format echoes : M/d/yy
original posted date : 01/27/12
$date echo result :Jan 26, 2012 4:00:00 PM


问:
Copy item and add it to list based on chance
The function reproduce takes 3 arguments:
viruses( a list of viruses). mutationProb(float 0-1 chance to mutate only when reproducing) and reproductionProb(float 0-1 chance to reproduce). So a float of 0.2, 0.4 would give it a 40% to reproduce, and if it reproduces a 20% chance to mutate.

I already wrote the mutate function, it works correctly :

```<code>def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from
    # the mutations to choose from
    mutations = [i for i in 'ATCG' if i != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]
</code>```

but my reproduce won't add the new viruses to the list if a virus reproduces ( based on reproductionProb), the new virus should be added to the already existing list of viruses,mutated or not,( mutate based on mutationProb ).

Each virus has an individual chance to reproduce

```<code>def reproduce(viruses, mutationProb, reproductionProb):
    for virus in viruses:
        if random.random() < reproductionProb:
            if random.random() < mutationProb:
                mutate(virus)
                viruses.append(virus)
            else:
                viruses.append(virus)
    return viruses
</code>```

Anyone got any idea on why my function doesn't do that already? As I see it it append the mutated virus based on the mutationProb, else it appends it without mutating.

答:
As Carcigenicate said, you want to make sure the random.random() < reproductionProb is evaluating to true as you would expect i.e. 4 in 10 times (or whatever).

As far as your code goes, if you always want to make a copy of the virus if it meets the reproduction criteria (40% chance) and then only mutate as well it if it meets the mutation criteria (20% chance), then you could simplify your code a little.

```<code>def reproduce(viruses, mutationProb, reproductionProb):
for virus in viruses:

    if random.random() < reproductionProb:
        if random.random() < mutationProb:
            mutate(virus)

        viruses.append(virus)

return viruses
</code>```

Body:
The function reproduce takes 3 arguments:
viruses( a list of viruses). mutationProb(float 0-1 chance to mutate only when reproducing) and reproductionProb(float 0-1 chance to reproduce). So a float of 0.2, 0.4 would give it a 40% to reproduce, and if it reproduces a 20% chance to mutate.

I already wrote the mutate function, it works correctly :

def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from
    # the mutations to choose from
    mutations = [i for i in 'ATCG' if i != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]

but my reproduce won't add the new viruses to the list if a virus reproduces ( based on reproductionProb), the new virus should be added to the already existing list of viruses,mutated or not,( mutate based on mutationProb ).

Each virus has an individual chance to reproduce

def reproduce(viruses, mutationProb, reproductionProb):
    for virus in viruses:
        if random.random() < reproductionProb:
            if random.random() < mutationProb:
                mutate(virus)
                viruses.append(virus)
            else:
                viruses.append(virus)
    return viruses

Anyone got any idea on why my function doesn't do that already? As I see it it append the mutated virus based on the mutationProb, else it appends it without mutating.

Body:
As Carcigenicate said, you want to make sure the random.random() < reproductionProb is evaluating to true as you would expect i.e. 4 in 10 times (or whatever).

As far as your code goes, if you always want to make a copy of the virus if it meets the reproduction criteria (40% chance) and then only mutate as well it if it meets the mutation criteria (20% chance), then you could simplify your code a little.

def reproduce(viruses, mutationProb, reproductionProb):
for virus in viruses:

    if random.random() < reproductionProb:
        if random.random() < mutationProb:
            mutate(virus)

        viruses.append(virus)

return viruses


问:
JavaScript: Compare dates in an array and sum the "price" for each month/year
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

```<code>transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}
</code>```

JavaScript:

```<code>request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};
</code>```

I tried to loop over the json object but I struggle to find a solution to compare the dates.

答:
Edit: Edited example with Object.assign instead of Object spread.

You'll need to use reduce to sum the prices. See comments for details.

const transactions = [{
    date: "2017-11-17",
    price: "28",
  },
  {
    date: "2017-12-17",
    price: "23",
  },
  {
    date: "2017-11-17",
    price: "12",
  },
  {
    date: "2017-10-17",
    price: "55",
  },
  {
    date: "2017-11-17",
    price: "09",
  },
];

const sumTransactions = (transactions) => {

  const summed = transactions.reduce((acc, current) => {
    // Get the current date object
    const date = new Date(current.date);
    // Create your key/identifier
    const key = `${date.getFullYear()}-${date.getMonth() + 1}`;
    // Retreive the previous price from the accumulator
    const previousPrice = acc[key]; // Might also return undefined
    // Create your temp current price value, and be sure to deal with numbers.
    let currentPrice = Number(current.price);
    // If you had a previous value (and not undefined)
    if (previousPrice) {
      // Add it to our value
      currentPrice += Number(previousPrice);
    }
    // Return the future accumulator value
    return Object.assign(acc, {
      [key]: currentPrice, // new values will overwrite same old values
    })
  }, {})

  // Once we have all values, get the dates, and sort them (default: earlier first)
  // Return an array of each value from the summed object to our sortedArray
  const sortedArray = Object.keys(summed).sort().map((val) => {
    return summed[val];
  });

  console.log("sortedArray", sortedArray);
};

sumTransactions(transactions);```

Body:
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

I tried to loop over the json object but I struggle to find a solution to compare the dates.