问:
Kentico - Display query string as value of input field
I want to display the query string (if it's not empty) as the value of an input field, something like this <input name="campaign" type="hidden" value="ABC Campaign {% if (QueryString.GetValue("utm_source") != null) { return "| QueryString.GetValue("utm_source")"} %}" />

but couldn't make it work due to all the double quotes. I've tried escaping the quotes with back slash but didn't work. Could you help?
(The above code is placed inside the Form > Layout)

答:
Use single quote to wrap entire statement and remove quotes for return statement:</p>

```<code>value='ABC Campaign {% if (QueryString.GetValue("utm_source") != null) { return  QueryString.GetValue("utm_source")} %}'
</code>```

Body:
Use single quote to wrap entire statement and remove quotes for return statement:

value='ABC Campaign {% if (QueryString.GetValue("utm_source") != null) { return  QueryString.GetValue("utm_source")} %}'


来源: stackexchange

问:
Seeing how many values in two SparkR columns match
I have two integer columns (x1 and x2) in a SparkR DataFrame named df that are very similar to each other. I want to get a count of how many of the values match and compare it with the total length of the columns. How can I do this? I have tried the following, both of which result in errors.

```<code>agg(df, sum(df$x1==df$x2))
collect(sum(df$x1==df$x2))
</code>```

答:
Specifically, here's the code to the answer:</p>

```<code>df <- withColumn(df, 'x', df$x1==df$x2)
head(agg(groupBy(df, 'x'), x="count"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two integer columns (x1 and x2) in a SparkR DataFrame named df that are very similar to each other. I want to get a count of how many of the values match and compare it with the total length of the columns. How can I do this? I have tried the following, both of which result in errors.

agg(df, sum(df$x1==df$x2))
collect(sum(df$x1==df$x2))

Body:
Specifically, here's the code to the answer:

df <- withColumn(df, 'x', df$x1==df$x2)
head(agg(groupBy(df, 'x'), x="count"))


问:
ModSecurity - disable logging to standard Apache error log
I'm wondering if there is some way in ModSecurity Apache2 module (version 2.9.1) how to log error messages into log file specified by the SecDebugLog option but don't duplicate them into the standard Apache error log file?

According to ModSecurity documentation the error messages are always doubled in both log files: Messages with levels 1–3 are designed to be meaningful, and are copied to the Apache’s error log. But I'd like to keep the ModSecurity stuff separate and don't mess the standard error log.

答:
You can remove log from any of the Rules and just leave auditlog.

If using the OWASP CRS then change the default action from this:

```<code>SecDefaultAction "phase:1,deny,log"
SecDefaultAction "phase:2,deny,log"
</code>```

to this:

```<code>SecDefaultAction "phase:1,deny,nolog,auditlog"
SecDefaultAction "phase:2,deny,nolog,auditlog"
</code>```

Which will turn off all logging, but then turn on auditlogging again.

You may also want to add similar for phase 3 and 4 depending on whether you are also checkout outbound traffic.

However I would really, really, really caution against this for a number of reasons:

You will eventually block something with a ModSecurity rule and wonder why it's happening and skip over the Audit log and blame Apache. Trust me. "Why is this request returning 403 when I can see the page exists?!?!" At least if in the error log then you've another chance to see why this is so.

The entry in the error log is in one line. This makes it much easier to collect, parse and deal with errors in tools like Splunk. The audit log is spread over several lines so is less machine readable. And you should be reviewing your WAF logs regularly and not just assuming it's working correctly and only look at logs when something goes wrong. Maybe not in detail at each log level but in summary. Ivan Ristic, the original creator of ModSecurity, recently tweeted:

"If you’re not using your WAF as an IDS, you’re doing it wrong."

These are errors. And the error log is therefore the right place for them. The audit log is then a useful place to get extra detail if you cannot explain the errors.

Body:
You can remove log from any of the Rules and just leave auditlog.

If using the OWASP CRS then change the default action from this:

SecDefaultAction "phase:1,deny,log"
SecDefaultAction "phase:2,deny,log"

to this:

SecDefaultAction "phase:1,deny,nolog,auditlog"
SecDefaultAction "phase:2,deny,nolog,auditlog"

Which will turn off all logging, but then turn on auditlogging again.

You may also want to add similar for phase 3 and 4 depending on whether you are also checkout outbound traffic.

However I would really, really, really caution against this for a number of reasons:

You will eventually block something with a ModSecurity rule and wonder why it's happening and skip over the Audit log and blame Apache. Trust me. "Why is this request returning 403 when I can see the page exists?!?!" At least if in the error log then you've another chance to see why this is so.

The entry in the error log is in one line. This makes it much easier to collect, parse and deal with errors in tools like Splunk. The audit log is spread over several lines so is less machine readable. And you should be reviewing your WAF logs regularly and not just assuming it's working correctly and only look at logs when something goes wrong. Maybe not in detail at each log level but in summary. Ivan Ristic, the original creator of ModSecurity, recently tweeted:

"If you’re not using your WAF as an IDS, you’re doing it wrong."

These are errors. And the error log is therefore the right place for them. The audit log is then a useful place to get extra detail if you cannot explain the errors.


问:
PHP HTML table retrieve multiple data in one  tag
I'm trying to generate a list from database in a HTML table just like image below;

https://i.stack.imgur.com/61XLl.png

And here's what i did;

https://i.stack.imgur.com/lLsvF.png

And the code;

```<code>    <table cellpadding="3" border="1"  style="width:100%;margin-top:30px; margin-bottom:50px; font-size:12px">
    <thead>
        <tr>
            <th>KURSUS</th>
            <th rowspan="2">NAMA PENSYARAH</th>
            <th rowspan="2">NO. SIRI</th>
        </tr>
        <tr>
            <th>NAMA</th>
        </tr>
    </thead>
    <tbody align="center">
        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

        <tr>
            <td><?php echo $row['po_name']; ?></td>
            <?php while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();?>
            <td><?php echo $rowname['user_name']; ?></td>
            <td><?php echo $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']; ?></td>
            <?php } ?>
        </tr>

                    <?php
                }
            }
        ?>
    </tbody>
</table>
</code>```

Help me. Thank you in advance :)

答:
Put the  outside the <?php while($rowlist = $list->fetch_assoc()){

Or get all your data before you start display html and store it in a multi-dimensional array. Then simply loop through the data array. That way you won't have as much php mixed with html also.

Title: PHP HTML table retrieve multiple data in one <td> tag

Body:
I'm trying to generate a list from database in a HTML table just like image below;

https://i.stack.imgur.com/61XLl.png

And here's what i did;

https://i.stack.imgur.com/lLsvF.png

And the code;

            KURSUS
            NAMA PENSYARAH
            NO. SIRI

            NAMA

        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

            <?php echo $row['po_name']; ?>
            <?php while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();?>
            <?php echo $rowname['user_name']; ?>
            <?php echo $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']; ?>
            <?php } ?>

                    <?php
                }
            }
        ?>

Help me. Thank you in advance :)

Body:
Put the <td> outside the <?php while($rowlist = $list->fetch_assoc()){

Or get all your data before you start display html and store it in a multi-dimensional array. Then simply loop through the data array. That way you won't have as much php mixed with html also.


问:
How to suppress the "Stage 2===>" from the output console in spark?
I have dataframe and trying to get distinct count and able to get distinct count successfully but whenever scala program is executing i'm getting this message <code>([Stage 2:=============================>                             (1 + 1) / 2])</code>how can i suppress particular this message in console.  </p>

```<code>val countID = dataDF.select(substring(col("dataDF"),5,7).distinct().count()
</code>```

答:
You need to set spark.ui.showConsoleProgress to false

I found this in the comments of the ticket for the addition of the progress bar.

https://issues.apache.org/jira/browse/SPARK-4017

I haven't seen it in any of the documentation though, it really should be added.

Body:
I have dataframe and trying to get distinct count and able to get distinct count successfully but whenever scala program is executing i'm getting this message ([Stage 2:=============================>                             (1 + 1) / 2])how can i suppress particular this message in console.

val countID = dataDF.select(substring(col("dataDF"),5,7).distinct().count()


问:
Spark Java round each value in dataframe to two decimal places.
I have a dataframe in spark that has 10 columns and 100ish rows. Each cell in the dataframe contains a decimal number. I want to round all the decimal numbers to two decimal places. How can I do this in Java?</p>

答:
you can do this with the function public static Column round(Column e, int scale) :

https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/functions.html#round(org.apache.spark.sql.Column,%20int)


问:
Redirecting to site from an existing button being clicked
I'm quite new to coding. I have a button with the ID='test'. I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked.

Button:

```<code><button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">
</code>```

I tried running this:

```<code><script>
document.getElementById("test").onclick = window.location='http://www.google.com/'
</script>
</code>```

However, this would redirect straight away. I want it to redirect only when the button is clicked. Please help me fix this.

Many thanks.

答:
I would suggest use onclick on button, for example

your button will look like this

<button id="test" onclick="redirect()">Redirect</button>

Now in the script write the redirect function as

```<code><script>
  function redirect() {
    window.location.href = "http://www.google.com/";
  }
</script>
</code>```

Body:
I'm quite new to coding. I have a button with the ID='test'. I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked.

Button:

<button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">

I tried running this:

However, this would redirect straight away. I want it to redirect only when the button is clicked. Please help me fix this.

Many thanks.

Body:
I would suggest use onclick on button, for example

your button will look like this

<button id="test" onclick="redirect()">Redirect</button>

Now in the script write the redirect function as

<script>
  function redirect() {
    window.location.href = "http://www.google.com/";
  }
</script>


问:
Keeping track of how many instantiation of a Form is opened or closed
I have an application with three forms. MainForm, QuestionForm, and ViewItemsForm. The MainForm is always displayed. The MainForm contains two buttons and two read-only textboxes. One of the buttons allows the user to open up multiple instance of the QuestionForm which should then display the count of how many are open in one of the textboxes in the MainForm. If one of the QuestionForms is closed, the count inside the textbox should go down to.

I've tried to implement the trigger inside the button that opens the QuestionFrom, and another when the form is closed, but it doesn't seem to work.

```<code>public partial class Form1 : Form
{
   private void questionFormButton_Click(object sender, EventArgs e)
   {
      QuestionForm questionFormOpen = new QuestionForm();
      questionFormOpen.Show();
   }

  private void countOfQuestionForm_TextChanged(object sender, EventArgs e)
  {
     countOfQuestionForm.Text = //Assign the count here
  }

}
</code>```

答:
You can use the Application.OpenForms Property like the following code:

```<code>private void questionFormButton_Click(object sender, EventArgs e)
{
    QuestionForm questionFormOpen = new QuestionForm();
    questionFormOpen.Show();
    questionFormOpen.Shown += Fr_Closed;
    questionFormOpen.Disposed += Fr_Closed;
}
private void Fr_Closed(object sender, EventArgs e)
{
  countOfQuestionForm.Text = Application.OpenForms.OfType<QuestionForm>().Count().ToString();
}
</code>```

Body:
I have an application with three forms. MainForm, QuestionForm, and ViewItemsForm. The MainForm is always displayed. The MainForm contains two buttons and two read-only textboxes. One of the buttons allows the user to open up multiple instance of the QuestionForm which should then display the count of how many are open in one of the textboxes in the MainForm. If one of the QuestionForms is closed, the count inside the textbox should go down to.

I've tried to implement the trigger inside the button that opens the QuestionFrom, and another when the form is closed, but it doesn't seem to work.

public partial class Form1 : Form
{
   private void questionFormButton_Click(object sender, EventArgs e)
   {
      QuestionForm questionFormOpen = new QuestionForm();
      questionFormOpen.Show();
   }

  private void countOfQuestionForm_TextChanged(object sender, EventArgs e)
  {
     countOfQuestionForm.Text = //Assign the count here
  }

}

Body:
You can use the Application.OpenForms Property like the following code:

private void questionFormButton_Click(object sender, EventArgs e)
{
    QuestionForm questionFormOpen = new QuestionForm();
    questionFormOpen.Show();
    questionFormOpen.Shown += Fr_Closed;
    questionFormOpen.Disposed += Fr_Closed;
}
private void Fr_Closed(object sender, EventArgs e)
{
  countOfQuestionForm.Text = Application.OpenForms.OfType<QuestionForm>().Count().ToString();
}


问:
C++ zlib inflate failing - translation of c# fixup?
I'm trying to inflate a string using zlib's deflate, but it's failing, apparently because it doesn't have the right header. I read elsewhere that the C# solution to this problem is:

```<code>public static byte[] FlateDecode(byte[] inp, bool strict) {
    MemoryStream stream = new MemoryStream(inp);
    InflaterInputStream zip = new InflaterInputStream(stream);
    MemoryStream outp = new MemoryStream();
    byte[] b = new byte[strict ? 4092 : 1];
    try {
        int n;
        while ((n = zip.Read(b, 0, b.Length)) > 0) {
            outp.Write(b, 0, n);
        }
        zip.Close();
        outp.Close();
        return outp.ToArray();
    }
    catch {
        if (strict)
            return null;
        return outp.ToArray();
    }
}
</code>```

But I know nothing about C#. I can surmise that all it's doing is adding a prefix to the string, but what that prefix is, I have no idea. Would someone be able to phrase this function (or even just the header creation and string concatenation) in C++?

The data which I'm trying to inflate is taken from a PDF using zlib deflation.

Thanks a million,
Wyatt

答:
I can't see any prefixes, sorry. Here's what the logic appears to be; sorry this isn't in C++:

```<code>MemoryStream stream = new MemoryStream(inp);
InflaterInputStream zip = new InflaterInputStream(stream);
</code>```

Create an inflate stream from the data passed

```<code>MemoryStream outp = new MemoryStream();
</code>```

Create a memory buffer stream for output

```<code>byte[] b = new byte[strict ? 4092 : 1];
try {
    int n;
    while ((n = zip.Read(b, 0, b.Length)) > 0) {
</code>```

If you're in strict mode, read up to 4092 bytes - or 1 in non-strict mode - into a byte buffer

```<code>        outp.Write(b, 0, n);
</code>```

Write all the bytes decoded (may be less than the 4092) to the output memory buffer stream

```<code>    zip.Close();
    outp.Close();
    return outp.ToArray();
</code>```

Clean up, and return the output memory buffer stream as an array.

I'm a bit confused, though: why not just cut array b off at n elements and return that rather than go via a MemoryStream? The code also ought really to take care to clean up the memory streams and zip on exception (e.g. using using) since they're all IDisposable but I guess that's not really important since they don't correspond to I/O file handles, only memory structures.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to inflate a string using zlib's deflate, but it's failing, apparently because it doesn't have the right header. I read elsewhere that the C# solution to this problem is:

public static byte[] FlateDecode(byte[] inp, bool strict) {
    MemoryStream stream = new MemoryStream(inp);
    InflaterInputStream zip = new InflaterInputStream(stream);
    MemoryStream outp = new MemoryStream();
    byte[] b = new byte[strict ? 4092 : 1];
    try {
        int n;
        while ((n = zip.Read(b, 0, b.Length)) > 0) {
            outp.Write(b, 0, n);
        }
        zip.Close();
        outp.Close();
        return outp.ToArray();
    }
    catch {
        if (strict)
            return null;
        return outp.ToArray();
    }
}

But I know nothing about C#. I can surmise that all it's doing is adding a prefix to the string, but what that prefix is, I have no idea. Would someone be able to phrase this function (or even just the header creation and string concatenation) in C++?

The data which I'm trying to inflate is taken from a PDF using zlib deflation.

Thanks a million,
Wyatt

Body:
I can't see any prefixes, sorry. Here's what the logic appears to be; sorry this isn't in C++:

MemoryStream stream = new MemoryStream(inp);
InflaterInputStream zip = new InflaterInputStream(stream);

Create an inflate stream from the data passed

MemoryStream outp = new MemoryStream();

Create a memory buffer stream for output

byte[] b = new byte[strict ? 4092 : 1];
try {
    int n;
    while ((n = zip.Read(b, 0, b.Length)) > 0) {

If you're in strict mode, read up to 4092 bytes - or 1 in non-strict mode - into a byte buffer

        outp.Write(b, 0, n);

Write all the bytes decoded (may be less than the 4092) to the output memory buffer stream

    zip.Close();
    outp.Close();
    return outp.ToArray();

Clean up, and return the output memory buffer stream as an array.

I'm a bit confused, though: why not just cut array b off at n elements and return that rather than go via a MemoryStream? The code also ought really to take care to clean up the memory streams and zip on exception (e.g. using using) since they're all IDisposable but I guess that's not really important since they don't correspond to I/O file handles, only memory structures.


问:
What happens if you set role = "" on an HTML element?
I am using ReactJS to create a generic wrapper component. I want to pass in role as a propType and on my rendered div have something like
.

My question is, what if a role isn't passed in and I end up with
?  Will that mess up screen readers, etc.?

I don't want to make it a required prop because this is just a generic wrapper div and not all elements will have a role.

答:
No, it shouldn't mess anything up.

As far as a browser is concerned, there's not really any difference between
 and

Body:
No, it shouldn't mess anything up.

As far as a browser is concerned, there's not really any difference between <div role=""> and <div>


问:
Flex-box: Align last row to grid
I have a simple flex-box layout with a container like:

```<code>.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
</code>```

Now I want the items in the last row to be aligned with the other. justify-content: space-between; should be used because the width and height of the grid can be adjusted.

Currently it looks like

Here, I want the item in the bottom right to be in the "middle column". What is the simplest way to accomplish that? Here is a small jsfiddle that shows this behaviour.

.exposegrid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.exposetab {
  width: 100px;
  height: 66px;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="exposegrid">
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
  <div class="exposetab"></div>
</div></code>```

答:
Yes.! We can but with some media queries & Maximum no of columns are predefined.

Here am using 4 columns. Check my code:

.container {
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  flex-flow: row wrap;
  -webkit-flex-flow: row wrap;
  -moz-flex-flow: row wrap;
}

.container .item {
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  justify-content: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  flex-basis: 25%; //max no of columns in %, 25% = 4 Columns
}

.container .item .item-child {
  width: 130px;
  height: 180px;
  background: red;
  margin: 10px;
}

@media (max-width: 360px) {
  .container .item {
    flex-basis: 100%;
  }
}

@media (min-width:360px) and (max-width: 520px) {
  .container .item {
    flex-basis: 50%;
  }
}

@media (min-width:520px) and (max-width: 680px) {
  .container .item {
    flex-basis: 33.33%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="item">
    <div class="item-child">1</div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>

</div></code>```

NOTE

1) No need to create child div. It may be any other tag like 'img' r whatever you want..

2) If you want more columns adjust the media queries and maximum no.of columns.

ContentLicense: CC BY-SA 4.0

Title: Flex-box: Align last row to grid

Body:
I have a simple flex-box layout with a container like:

.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

Now I want the items in the last row to be aligned with the other. justify-content: space-between; should be used because the width and height of the grid can be adjusted.

Currently it looks like

Here, I want the item in the bottom right to be in the "middle column". What is the simplest way to accomplish that? Here is a small jsfiddle that shows this behaviour.

.exposegrid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.exposetab {
  width: 100px;
  height: 66px;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  margin-bottom: 10px;
}

Body:
Yes.! We can but with some media queries & Maximum no of columns are predefined.

Here am using 4 columns. Check my code:

.container {
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  flex-flow: row wrap;
  -webkit-flex-flow: row wrap;
  -moz-flex-flow: row wrap;
}

.container .item {
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  justify-content: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  flex-basis: 25%; //max no of columns in %, 25% = 4 Columns
}

.container .item .item-child {
  width: 130px;
  height: 180px;
  background: red;
  margin: 10px;
}

@media (max-width: 360px) {
  .container .item {
    flex-basis: 100%;
  }
}

@media (min-width:360px) and (max-width: 520px) {
  .container .item {
    flex-basis: 50%;
  }
}

@media (min-width:520px) and (max-width: 680px) {
  .container .item {
    flex-basis: 33.33%;
  }
}

<div class="container">

  <div class="item">
    <div class="item-child">1</div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>
  <div class="item">
    <div class="item-child"></div>
  </div>

</div>

NOTE

1) No need to create child div. It may be any other tag like 'img' r whatever you want..

2) If you want more columns adjust the media queries and maximum no.of columns.


问:
Cordova DeviceReady not firing
I've been banging my head on this one for a few days. After getting a number of "object not defined" errors when trying to create a new FileTransfer() object, it looks like the problem is more basic -- somehow the DeviceReady event is not firing.

Stack Overflow has a lot of hits on this issue, but most of them have to do with pre-3.x cordova builds that had a different architecture (I'm on 4.1.2). I've tried the suggestions in the newer topics I could find -- removing and adding plugins, updating cordova, etc. -- to no avail. To try to isolate the issue, I've commented out the startup code to just a few lines:

Index.html:

```<code><!DOCTYPE html>
<html>
<head>
  <title>Blah</title>
  <meta charset="utf-8"/>
  <meta name="viewport" content="initial-scale=1, user-scalable=no, minimum-scale=1, maximum-scale=1">
  <link href="res/topcoat/css/topcoat-mobile-light.min.css" rel="stylesheet">
  <link href="res/css/styles.css" rel="stylesheet">
  <link href="res/css/pageslider.css" rel="stylesheet">
  <script data-main="js/main" src="lib/require.js"></script>
</head>
</code>```

Main.js:

```<code>require(["app/Application"], function (Application) {
  "use strict";

  document.addEventListener("deviceready", function(){
      $('body').html("<p>device is ready</p>");
  },true);

  $('body').html("<p>waiting...</p>");
});
</code>```

Instead of displaying "device is ready" in the body after a bit, the screen just displays "waiting...". This happens on both the iOS emulator and the browser (cordova emulate browser).

Cordova info:

```<code>$ cordova -v
4.1.2
</code>```

Plugin info:

```<code>$ cordova plugins
org.apache.cordova.globalization 0.3.3 "Globalization"
</code>```

(I get the same results if Globalization isn't there).

Is there some other place I should be looking? I'm running from the command line, if that makes a difference.

答:
I recently had this same issue, but in my case cordova.js was already properly included.

Eventually what worked for me was a simple remove and add of the ios platform:

```<code>cordova platform remove ios
cordova platform add ios
</code>```

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.

Title: Cordova DeviceReady not firing

Body:
I've been banging my head on this one for a few days. After getting a number of "object not defined" errors when trying to create a new FileTransfer() object, it looks like the problem is more basic -- somehow the DeviceReady event is not firing.

Stack Overflow has a lot of hits on this issue, but most of them have to do with pre-3.x cordova builds that had a different architecture (I'm on 4.1.2). I've tried the suggestions in the newer topics I could find -- removing and adding plugins, updating cordova, etc. -- to no avail. To try to isolate the issue, I've commented out the startup code to just a few lines:

Index.html:

<!DOCTYPE html>

  <title>Blah</title>
  <meta charset="utf-8"/>
  <meta name="viewport" content="initial-scale=1, user-scalable=no, minimum-scale=1, maximum-scale=1">
  <link href="res/topcoat/css/topcoat-mobile-light.min.css" rel="stylesheet">
  <link href="res/css/styles.css" rel="stylesheet">
  <link href="res/css/pageslider.css" rel="stylesheet">

Main.js:

require(["app/Application"], function (Application) {
  "use strict";

  document.addEventListener("deviceready", function(){
      $('body').html("
device is ready
");
  },true);

  $('body').html("
waiting...
");
});

Instead of displaying "device is ready" in the body after a bit, the screen just displays "waiting...". This happens on both the iOS emulator and the browser (cordova emulate browser).

Cordova info:

$ cordova -v
4.1.2

Plugin info:

$ cordova plugins
org.apache.cordova.globalization 0.3.3 "Globalization"

(I get the same results if Globalization isn't there).

Is there some other place I should be looking? I'm running from the command line, if that makes a difference.

Body:
I recently had this same issue, but in my case cordova.js was already properly included.

Eventually what worked for me was a simple remove and add of the ios platform:

cordova platform remove ios
cordova platform add ios

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.


问:
Python- Multiple os.path.split()
Do you guys know a more intelligent way to do this ?

```<code>os.path.split(os.path.split(os.path.split(os.getcwd())[0])[0])[0]
</code>```

os.getcwd() is for example:

```<code>/my/path/to/my/directory
</code>```

I should get

```<code>/my/path/
</code>```

That is really an exaggeration and duplication of the os.path.split()

Thanks

答:
I would suggest you using os.sep:

os.sep.join(os.getcwd().split(os.sep)[:-3])

Title: Python- Multiple os.path.split()

Body:
Do you guys know a more intelligent way to do this ?

os.path.split(os.path.split(os.path.split(os.getcwd())[0])[0])[0]

os.getcwd() is for example:

/my/path/to/my/directory

I should get

/my/path/

That is really an exaggeration and duplication of the os.path.split()

Thanks


问:
How to set Kafka parameters from a properties file?
What I am doing currently is as below:

```<code>val topic = "mytopic"
val zkhosts = "localhost"
val zkports = "2181"
</code>```

Setting it in my code and then sending it to kafkastream function works, but I want to read it from .properties file. Is there any possible solution?

答:
Given this property file at /tmp/sample.properties

```<code>kafka.topic = "mytopic"
kafka.zkhost = "localhost"
kafka.zkports = 2191
</code>```

We could use the plain-old java Property API to load the properties:

```<code>import java.io.FileReader
val configFile = new java.io.File("/tmp/sample.properties")
val reader = new FileReader(configFile)
val props = new Properties()
props.load(reader)
reader.close()
</code>```

You could also use your favorite config library to load the property file as you would on any other program.

For example, you could use the popular typesafe config lib. There're many wrappers for Scala, but in its raw form you could do something like:

```<code>import com.typesafe.config.ConfigFactory
val configFile = new java.io.File("/tmp/sample.properties")
val kafkaConfig = ConfigFactory.parseFile(configFile)

import java.util.Properties
val kafkaProperties = new Properties()
kafkaProperties.put("zookeeper.hosts", kafkaConfig.getString("kafka.zkhost"))
kafkaProperties.put("zookeeper.port", kafkaConfig.getInt("kafka.zkports"):java.lang.Integer)
kafkaProperties.put("kafka.topic", kafkaConfig.getString("kafka.topic"))
</code>```

(There're many ways to make that nice and compact. Here I'm using the most common form)

Body:
What I am doing currently is as below:

val topic = "mytopic"
val zkhosts = "localhost"
val zkports = "2181"

Setting it in my code and then sending it to kafkastream function works, but I want to read it from .properties file. Is there any possible solution?

Body:
Given this property file at /tmp/sample.properties

kafka.topic = "mytopic"
kafka.zkhost = "localhost"
kafka.zkports = 2191

We could use the plain-old java Property API to load the properties:

import java.io.FileReader
val configFile = new java.io.File("/tmp/sample.properties")
val reader = new FileReader(configFile)
val props = new Properties()
props.load(reader)
reader.close()

You could also use your favorite config library to load the property file as you would on any other program.

For example, you could use the popular typesafe config lib. There're many wrappers for Scala, but in its raw form you could do something like:

import com.typesafe.config.ConfigFactory
val configFile = new java.io.File("/tmp/sample.properties")
val kafkaConfig = ConfigFactory.parseFile(configFile)

import java.util.Properties
val kafkaProperties = new Properties()
kafkaProperties.put("zookeeper.hosts", kafkaConfig.getString("kafka.zkhost"))
kafkaProperties.put("zookeeper.port", kafkaConfig.getInt("kafka.zkports"):java.lang.Integer)
kafkaProperties.put("kafka.topic", kafkaConfig.getString("kafka.topic"))

(There're many ways to make that nice and compact. Here I'm using the most common form)


问:
Compilation Error with go Kit
I cloned a project which uses go-kit, when I try to compile the project, I get an compilation error which is something like

```<code>./main.go:124: cannot use makePostEndpoint(svc) (type endpoint.Endpoint) as type "github.com/go-kit/kit/transport/http".DecodeRequestFunc in argument to "github.com/go-k
it/kit/transport/http".NewServer
</code>```

The snippet of code is as below

```<code>func main() {
    ctx := context.Background()
    svc := cayleyService{}

    postHandler := httptransport.NewServer(
        ctx,
        makePostEndpoint(svc),
        decodePostRequest,
        encodeResponse,
    )
}

func makeGetEndpoint(svc CayleyService) endpoint.Endpoint {
    return func(ctx context.Context, request interface{}) (interface{}, error) {
        req := request.(getRequest)
        v, err := svc.Get(req.Qu)
        if err != nil {
            return getResponse{v, err.Error()}, nil
        }
        return getResponse{v, ""}, nil
    }
}
</code>```

I have version 1.8.1 of golang installed.

答: I found the issue. There is a newer version of go kit  in which the signature of the NewServer has changed. Context has been removed and hence. I just had to remove the ctx and everything compiled.</p>

Title: Compilation Error with go Kit

Body:
I cloned a project which uses go-kit, when I try to compile the project, I get an compilation error which is something like

./main.go:124: cannot use makePostEndpoint(svc) (type endpoint.Endpoint) as type "github.com/go-kit/kit/transport/http".DecodeRequestFunc in argument to "github.com/go-k
it/kit/transport/http".NewServer

The snippet of code is as below

func main() {
    ctx := context.Background()
    svc := cayleyService{}

    postHandler := httptransport.NewServer(
        ctx,
        makePostEndpoint(svc),
        decodePostRequest,
        encodeResponse,
    )
}

func makeGetEndpoint(svc CayleyService) endpoint.Endpoint {
    return func(ctx context.Context, request interface{}) (interface{}, error) {
        req := request.(getRequest)
        v, err := svc.Get(req.Qu)
        if err != nil {
            return getResponse{v, err.Error()}, nil
        }
        return getResponse{v, ""}, nil
    }
}

I have version 1.8.1 of golang installed.


问:
Is it legit to sign two apps with two different keystores, if need to be distributed under one company name?
I have a situation, where I might use two keystores for two different applications made in the same company, one with Android and one with Unity. But I have never seen any company to use more than one Keystore for signing their apps, I have verified this comparing Google, Facebook, etc apps. So, is it legit according to the market and logical according to the devs to have two keystores for the two apps made by the same company.

Note : We need to distribute the apps over the world.

答:
It is perfectly legal to do so, however more annoying. You can use the SAME keystore to sign any number of apps and there is absolutely no issue in doing so. The only argument I can think of in regards to why you would want to use more than one keystore is if you were planning on selling one of those apps to someone else. Then using a separate keystore per app is useful as you could just give them the keystore/password used to sign the app and you wouldn't have to worry about changing the keystores for all of the other apps you used that keystore with.

Does that make sense?


问:
Horizonatally align Crosstab on page
My product catalog displays a list of available stock with images. I use a crosstab to display the stock with sizes at the bottom of the page and an image of the product in middle.

How can I align the crosstab in the horizontal center of the page? Crosstab items can grow according to sizes available in stock.

答:
This isn't something Crystal supports. Your best option is to approximate the position you want formulaically. Click the x+2 button when setting the crosstab's Size and Position:

You can write a formula here that will alter the X position of the crosstab based on whatever fomula you like. I'd recommend setting up a Running Total to count the number of "sizes available in stock" (and if you want to get really precise, you can calculate a rough guess of the length of each column name based on the number of chars in the string.)

Otherwise there's really not a good way to handle this in Crystal.

Title: Horizonatally align Crosstab on page


问:
How to break a csv column to several different columns based on words?
I have a data set in a csv file that is in one column, but each row in the column contains data that could be column data with a value. I'm not sure how to parse the data so that the data is broken up by what would be the column data and the related value. The data looks something like this:

Column A,row1:

```<code>Name:Jane Doe
ID:123456
Company: J.Crew
Allergies: None
Age:25
Job Title: Analyst
</code>```

Column A, row2:

```<code>Name: John Doe
ID: 654321
Company:Banana Republic
Allergies: peanuts
Age:32
Job Title:Manager
</code>```

There are a hundred rows similar to these and I want it turn the data into a Name column, ID column, Company column, Age column, Job title column. I want to remove allergies item.

Example CSV file:

答:
I'll look up some example code later but here is the logic:

Create a string to hold the new data (myNewData)

Open the file

Read the file line by line

Split the line by a colon

Identify the first word in the line (the first part of the split)

If the first word is not "Name:" and is not allergies, then add a comma and the value (second part of the split from 4, with a trim of the whitespace). Append this to myNewData.

If the first word is allergies, then discard and start the next loop

If the first word is "Name:", then add a newline ('\n') and the value.

When the process completes, write myNewData to a new file.

Example code below:

```<code>#! /usr/bin/env python

def decider(line):
    try:
        first_part, second_part = lines.split(':')
        if first_part not in ('Name', 'Allergies'):
            return ',' + second_part.strip()
        elif first_part == 'Name':
            return '\n' + second_part.strip()
        else:
            return ''
    except:
        return ''

with open('text.txt', 'r') as f:
    myNewData = 'Name,ID,Company,Age,Job'
    for lines in f.readlines():
        myNewData += decider(lines)
    # print(myNewData)
    with open('output.csv', 'w') as fo:
        fo.write(myNewData)
</code>```

and you have a nice, new csv.

The output will look like:

Name,ID,Company,Age,Job

Jane Doe,123456,J.Crew,25,Analyst

John Doe,654321,Banana Republic,32,Manager

Body:
I have a data set in a csv file that is in one column, but each row in the column contains data that could be column data with a value. I'm not sure how to parse the data so that the data is broken up by what would be the column data and the related value. The data looks something like this:

Column A,row1:

Name:Jane Doe
ID:123456
Company: J.Crew
Allergies: None
Age:25
Job Title: Analyst

Column A, row2:

Name: John Doe
ID: 654321
Company:Banana Republic
Allergies: peanuts
Age:32
Job Title:Manager

There are a hundred rows similar to these and I want it turn the data into a Name column, ID column, Company column, Age column, Job title column. I want to remove allergies item.

Example CSV file:

Body:
I'll look up some example code later but here is the logic:

Create a string to hold the new data (myNewData)

Open the file

Read the file line by line

Split the line by a colon

Identify the first word in the line (the first part of the split)

If the first word is not "Name:" and is not allergies, then add a comma and the value (second part of the split from 4, with a trim of the whitespace). Append this to myNewData.

If the first word is allergies, then discard and start the next loop

If the first word is "Name:", then add a newline ('\n') and the value.

When the process completes, write myNewData to a new file.

Example code below:

#! /usr/bin/env python

def decider(line):
    try:
        first_part, second_part = lines.split(':')
        if first_part not in ('Name', 'Allergies'):
            return ',' + second_part.strip()
        elif first_part == 'Name':
            return '\n' + second_part.strip()
        else:
            return ''
    except:
        return ''

with open('text.txt', 'r') as f:
    myNewData = 'Name,ID,Company,Age,Job'
    for lines in f.readlines():
        myNewData += decider(lines)
    # print(myNewData)
    with open('output.csv', 'w') as fo:
        fo.write(myNewData)

and you have a nice, new csv.

The output will look like:

Name,ID,Company,Age,Job

Jane Doe,123456,J.Crew,25,Analyst

John Doe,654321,Banana Republic,32,Manager


问:
GCC ppc64 aligned functions
I'm using GCC for make some powerpc64 executable, but sometimes between functions i have the following mistakes: Screenshot

Powerpc instructions format are still in 4 bytes, i tried some gcc commands (-fno-align-functions) but the compiler still fill bytes between functions.

I want my functions start directly after the end of the previous functions, without any values/zero filled (in the case of the screenshots the functions should start at 0x124).

Thanks.

答:
The PPC64 ABI specifies a traceback table appended to functions.  The zeroes may be due to the traceback table and not related to alignment.  Try using the
-mtraceback=no command line option.

Title: GCC ppc64 aligned functions


问:
Rails: Validating min and max length of a string but allowing it to be blank
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

```<code>validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5
</code>```

How do I write this to accomplish my goal?

答:
From the validates_length_of documentation:

```<code>validates_length_of :phone, :in => 7..32, :allow_blank => true
</code>```

:allow_blank - Attribute may be blank; skip validation.

Body:
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5

How do I write this to accomplish my goal?

Body:
From the validates_length_of documentation:

validates_length_of :phone, :in => 7..32, :allow_blank => true

:allow_blank - Attribute may be blank; skip validation.


问:
Search icon not working in css
I am using the following code for css:

```<code>#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
</code>```

Search Box:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
</code>```

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.

答: It seems to be working correctly for me, I would just double check to see that your path is correct for image and also make sure that the css file is correctly referenced in the html</p>

Title: Search icon not working in css

Body:
I am using the following code for css:

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

Search Box:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.


问:
Use data binding to set View visibility
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

```<code><data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>
</code>```

答:
The problem is that visibility is an Integer on the View class, this means you have two ways to make this work:

Use the View.VISIBLE and View.GONE constants. https://developer.android.com/topic/libraries/data-binding/index.html#imports

Define a custom setter for visibility that takes a Boolean. https://developer.android.com/topic/libraries/data-binding/index.html#custom_setters

Possible implementation:

```<code>@BindingAdapter("android:visibility")
public static void setVisibility(View view, Boolean value) {
    view.setVisibility(value ? View.VISIBLE : View.GONE);
}
</code>```

Which will make <FrameLayout android:visibility="@{sale}"/> work.

Title: Use data binding to set View visibility

Body:
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

<data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>

Body:
The problem is that visibility is an Integer on the View class, this means you have two ways to make this work:

Use the View.VISIBLE and View.GONE constants. https://developer.android.com/topic/libraries/data-binding/index.html#imports

Define a custom setter for visibility that takes a Boolean. https://developer.android.com/topic/libraries/data-binding/index.html#custom_setters

Possible implementation:

@BindingAdapter("android:visibility")
public static void setVisibility(View view, Boolean value) {
    view.setVisibility(value ? View.VISIBLE : View.GONE);
}

Which will make <FrameLayout android:visibility="@{sale}"/> work.


问:
Using sass with Flask and jinja2
I would like to include a sass compiler in my Flask application. Is there a generally accepted way of doing this?</p>

答:
Currently, exist a better approach for this issue, the extion Flask-Scss.

You just have to install it: pip install Flask-Scss

And instanciate a Scss object after configuring the application (probably in your manage.py file):

```<code>from flask import Flask
from flask.ext.scss import Scss

app = Flask(__name__)
Scss(app)
</code>```

By default, the extension will look for your .scss files in {app.root_dir}/assets/scss or {app.root_dir}/assets and will put the generate .css files in {default_static_dir}/css or {default_static_dir}.

Title: Using sass with Flask and jinja2

Body:
Currently, exist a better approach for this issue, the extion Flask-Scss.

You just have to install it: pip install Flask-Scss

And instanciate a Scss object after configuring the application (probably in your manage.py file):

from flask import Flask
from flask.ext.scss import Scss

app = Flask(__name__)
Scss(app)

By default, the extension will look for your .scss files in {app.root_dir}/assets/scss or {app.root_dir}/assets and will put the generate .css files in {default_static_dir}/css or {default_static_dir}.


答:
I think it might need something like:

```<code>validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true
</code>```

More examples: ActiveRecord::Validations::ClassMethods

Title: Rails: Validating min and max length of a string but allowing it to be blank

Body:
I think it might need something like:

validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true

More examples: ActiveRecord::Validations::ClassMethods


问:
Datetime comparison in C#
I have the current UTC datetime as follows:

```<code> public void GetUTCTime()
        {
            var now = DateTime.UtcNow;
            string utc = now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine("Current UTC time is: " + utc);
        }
</code>```

My another date is like,

```<code>String myDate = "2017-06-15 16:10:16";
</code>```

Now i have to find out which datetime is latest.

答:
Use DateTime.Compare:

if (DateTime.Compare(time_1, time_2) > 0) // if time_1 is later than time_2
{
    // Your code here
}
```

<hr>

<h2>According to the linked MSDN documentation:</h2>

<p>If the returned value is...</p>

<ul>
<li>Less than zero: time_1 is earlier than time_2</li>
<li>Zero: time_1 is the same as time_2</li>
<li>Greater than zero: time_1 is later than time_2</li>
</ul>

<h2>Converting the string date back to DateTime:</h2>

<p>Since you're using the date as a string, you have to convert it back to DateTime before comparing, like that:</p>

<pre class="lang-cs prettyprint-override"><code>DateTime convertedDate = DateTime.Parse(stringDate);
</code>```

Title: Datetime comparison in C#

Body:
I have the current UTC datetime as follows:

 public void GetUTCTime()
        {
            var now = DateTime.UtcNow;
            string utc = now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine("Current UTC time is: " + utc);
        }

My another date is like,

String myDate = "2017-06-15 16:10:16";

Now i have to find out which datetime is latest.

Body:
Use DateTime.Compare:

if (DateTime.Compare(time_1, time_2) > 0) // if time_1 is later than time_2
{
    // Your code here
}

According to the linked MSDN documentation:

If the returned value is...

Less than zero: time_1 is earlier than time_2

Zero: time_1 is the same as time_2

Greater than zero: time_1 is later than time_2

Converting the string date back to DateTime:

Since you're using the date as a string, you have to convert it back to DateTime before comparing, like that:

DateTime convertedDate = DateTime.Parse(stringDate);


问:
json object returning 'undefined" values along with actual values
So, I've looked through similar questions out here, but still couldn't find an answer to my query.
For some reason, I seem to get "undefined values along with my actual values in my json object. I receive these values from my php file. The code ffor the php file is as follows:

```<code>$sql = "SELECT distinct rackID FROM rackusage where startTime like '%".$curdate."%'";
$res = mysql_query($sql);
while($r = mysql_fetch_assoc($res)){

        // Queries to get respective values to put inside my array

        $temp[] = array('id' => (int) $r['rackID']);
        $temp[] = array('rackName' => (string) $rackname);
        $temp[] = array('uptime' => (int) $uptime);
        $temp[] = array('downtime' => (int) $downtime);
        $temp[] = array('utilization' => (int) $utilization);
    }   echo json_encode($temp);
</code>```

The output string is as follows:

[{"id":1},{"rackName":"xyz"},{"uptime":119},{"downtime":0},{"utilization":0},{"id":2},{"rackName":"abc"},{"uptime":122},{"downtime":0},{"utilization":0},{"id":3},{"rackName":"pqr"},{"uptime":114},{"downtime":0},{"utilization":0}]

The JS code is:

```<code>        function workwithdate(curdate){
            $.ajax({
               type: "Post",
                url: 'senddata.php',
                data:{'selectDate': curdate},
                async: false,
                success: function(data){
                    if(data){
                        alert(data);
                        recData= $.parseJSON(data);
                        //recData = data;
                        console.log(recData);
                         alert(recData);
                         alert(recData.length);

                        $.each(recData, function(idx, la){
                          var someid = la.id;
                            console.log(someid);
                          var rName = la.rackName;
                            console.log(rName);
                          var rUptime = la.uptime;
                            console.log(rUptime);
                        });
       }
                }
            });
        }
</code>```

My output looks like this:

TIA

答:
You want one associative array per row, so:</p>

```<code>while($r = mysql_fetch_assoc($res)){
    $temp[] = array(
        'id' => (int) $r['rackID'],
        'rackName' => (string) $rackname,
        'uptime' => (int) $uptime,
        'downtime' => (int) $downtime,
        'utilization' => (int) $utilization
    );
}
</code>```

Body:
So, I've looked through similar questions out here, but still couldn't find an answer to my query.
For some reason, I seem to get "undefined values along with my actual values in my json object. I receive these values from my php file. The code ffor the php file is as follows:

$sql = "SELECT distinct rackID FROM rackusage where startTime like '%".$curdate."%'";
$res = mysql_query($sql);
while($r = mysql_fetch_assoc($res)){

        // Queries to get respective values to put inside my array

        $temp[] = array('id' => (int) $r['rackID']);
        $temp[] = array('rackName' => (string) $rackname);
        $temp[] = array('uptime' => (int) $uptime);
        $temp[] = array('downtime' => (int) $downtime);
        $temp[] = array('utilization' => (int) $utilization);
    }   echo json_encode($temp);

The output string is as follows:

[{"id":1},{"rackName":"xyz"},{"uptime":119},{"downtime":0},{"utilization":0},{"id":2},{"rackName":"abc"},{"uptime":122},{"downtime":0},{"utilization":0},{"id":3},{"rackName":"pqr"},{"uptime":114},{"downtime":0},{"utilization":0}]

The JS code is:

        function workwithdate(curdate){
            $.ajax({
               type: "Post",
                url: 'senddata.php',
                data:{'selectDate': curdate},
                async: false,
                success: function(data){
                    if(data){
                        alert(data);
                        recData= $.parseJSON(data);
                        //recData = data;
                        console.log(recData);
                         alert(recData);
                         alert(recData.length);

                        $.each(recData, function(idx, la){
                          var someid = la.id;
                            console.log(someid);
                          var rName = la.rackName;
                            console.log(rName);
                          var rUptime = la.uptime;
                            console.log(rUptime);
                        });
       }
                }
            });
        }

My output looks like this:

TIA

Body:
You want one associative array per row, so:

while($r = mysql_fetch_assoc($res)){
    $temp[] = array(
        'id' => (int) $r['rackID'],
        'rackName' => (string) $rackname,
        'uptime' => (int) $uptime,
        'downtime' => (int) $downtime,
        'utilization' => (int) $utilization
    );
}


问:
Autodesk Forge and 416 (Requested Range Not Satisfiable)
I'm trying to send a Revit file to my Bucket chunk by chunk. My Revit file is almost 13 MB. Here is my code:

function handleFileSelect(evt) {
    var files = evt.target.files;
    var file = files[0];

    var segmentSize = 1024 * 1024 * 5; //5 MB
    var startingByte = 0;
    var endingByte = startingByte + segmentSize - 1;
    var segments = Math.ceil(file.size / segmentSize);
    var session = Math.floor(100000000 + Math.random() * -900000000);

    for (var i = 0; i < segments; i ++)
    {
        var blob = file.slice(startingByte, endingByte);
        var url = 'https://developer.api.autodesk.com/oss/v2/buckets/' + 'linked_model' + '/objects/' + file.name + '/resumable';
        //console.log(url);
        var contentRange = 'bytes ' + startingByte + '-' + endingByte + '/' + file.size;

        $.ajax({
            type: 'PUT',
            url: url,
            data: blob,
            headers: {
                'Authorization':'Bearer ' + token,
                'Content-Type':'application/octet-stream',
                'Content-Range': contentRange,
                'Session-Id': session
            },
            crossDomain: true,
            processData: false,
            success: function (data) {
                console.log(i);
                startingByte = endingByte + 1;
                endingByte = startingByte + segmentSize - 1;
                },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Status: " + textStatus); alert("Error: " + errorThrown);
                console.log(startingByte);
                console.log(endingByte);
                console.log(file.size);
            }
        });
    }
}```

It gives me error: 416 (Requested Range Not Satisfiable)

Can anyone help?

答:
I had the same 416 error but my issue was that I tried to upload chunks smaller than 2MB, which is not doable (except for the last chunk).

When I increased the chunks size to 5MB it started to work. I just wrote a blog article about it: https://forge.autodesk.com/blog/nailing-large-files-uploads-forge-resumable-api

Below is the core piece of code that handles chunking and uploading (in node.js).

By the way, I strongly discourage you to perform this kind of operation client-side as your snippet suggests, this means you have to pass a write-access token to the web page which compromises security of your app. You should first upload the file to your server and then securely upload it to Forge as described in the post and my sample.

```<code>/////////////////////////////////////////////////////////
// Uploads object to bucket using resumable endpoint
//
/////////////////////////////////////////////////////////
uploadObjectChunked (getToken, bucketKey, objectKey,
                     file,  opts = {}) {

  return new Promise((resolve, reject) => {

    const chunkSize = opts.chunkSize || 5 * 1024 * 1024

    const nbChunks = Math.ceil(file.size / chunkSize)

    const chunksMap = Array.from({
      length: nbChunks
    }, (e, i) => i)

    // generates uniques session ID
    const sessionId = this.guid()

    // prepare the upload tasks
    const uploadTasks = chunksMap.map((chunkIdx) => {

      const start = chunkIdx * chunkSize

      const end = Math.min(
          file.size, (chunkIdx + 1) * chunkSize) - 1

      const range = `bytes ${start}-${end}/${file.size}`

      const length = end - start + 1

      const readStream =
        fs.createReadStream(file.path, {
          start, end: end
        })

      const run = async () => {

        const token = await getToken()

        return this._objectsAPI.uploadChunk(
          bucketKey, objectKey,
          length, range, sessionId,
          readStream, {},
          {autoRefresh: false}, token)
      }

      return {
        chunkIndex: chunkIdx,
        run
      }
    })

    let progress = 0

    // runs asynchronously in parallel the upload tasks
    // number of simultaneous uploads is defined by
    // opts.concurrentUploads
    eachLimit(uploadTasks, opts.concurrentUploads || 3,
      (task, callback) => {

        task.run().then((res) => {

          if (opts.onProgress) {

            progress += 100.0 / nbChunks

            opts.onProgress ({
              progress: Math.round(progress * 100) / 100,
              chunkIndex: task.chunkIndex
            })
          }

          callback ()

        }, (err) => {

          console.log('error')
          console.log(err)

          callback(err)
        })

    }, (err) => {

        if (err) {

          return reject(err)
        }

        return resolve({
          fileSize: file.size,
          bucketKey,
          objectKey,
          nbChunks
        })
    })
  })
}
</code>```

Body:
I'm trying to send a Revit file to my Bucket chunk by chunk. My Revit file is almost 13 MB. Here is my code:

function handleFileSelect(evt) {
    var files = evt.target.files;
    var file = files[0];

    var segmentSize = 1024 * 1024 * 5; //5 MB
    var startingByte = 0;
    var endingByte = startingByte + segmentSize - 1;
    var segments = Math.ceil(file.size / segmentSize);
    var session = Math.floor(100000000 + Math.random() * -900000000);

    for (var i = 0; i < segments; i ++)
    {
        var blob = file.slice(startingByte, endingByte);
        var url = 'https://developer.api.autodesk.com/oss/v2/buckets/' + 'linked_model' + '/objects/' + file.name + '/resumable';
        //console.log(url);
        var contentRange = 'bytes ' + startingByte + '-' + endingByte + '/' + file.size;

        $.ajax({
            type: 'PUT',
            url: url,
            data: blob,
            headers: {
                'Authorization':'Bearer ' + token,
                'Content-Type':'application/octet-stream',
                'Content-Range': contentRange,
                'Session-Id': session
            },
            crossDomain: true,
            processData: false,
            success: function (data) {
                console.log(i);
                startingByte = endingByte + 1;
                endingByte = startingByte + segmentSize - 1;
                },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Status: " + textStatus); alert("Error: " + errorThrown);
                console.log(startingByte);
                console.log(endingByte);
                console.log(file.size);
            }
        });
    }
}

It gives me error: 416 (Requested Range Not Satisfiable)

Can anyone help?

Body:
I had the same 416 error but my issue was that I tried to upload chunks smaller than 2MB, which is not doable (except for the last chunk).

When I increased the chunks size to 5MB it started to work. I just wrote a blog article about it: https://forge.autodesk.com/blog/nailing-large-files-uploads-forge-resumable-api

Below is the core piece of code that handles chunking and uploading (in node.js).

By the way, I strongly discourage you to perform this kind of operation client-side as your snippet suggests, this means you have to pass a write-access token to the web page which compromises security of your app. You should first upload the file to your server and then securely upload it to Forge as described in the post and my sample.

/////////////////////////////////////////////////////////
// Uploads object to bucket using resumable endpoint
//
/////////////////////////////////////////////////////////
uploadObjectChunked (getToken, bucketKey, objectKey,
                     file,  opts = {}) {

  return new Promise((resolve, reject) => {

    const chunkSize = opts.chunkSize || 5 * 1024 * 1024

    const nbChunks = Math.ceil(file.size / chunkSize)

    const chunksMap = Array.from({
      length: nbChunks
    }, (e, i) => i)

    // generates uniques session ID
    const sessionId = this.guid()

    // prepare the upload tasks
    const uploadTasks = chunksMap.map((chunkIdx) => {

      const start = chunkIdx * chunkSize

      const end = Math.min(
          file.size, (chunkIdx + 1) * chunkSize) - 1

      const range = `bytes ${start}-${end}/${file.size}`

      const length = end - start + 1

      const readStream =
        fs.createReadStream(file.path, {
          start, end: end
        })

      const run = async () => {

        const token = await getToken()

        return this._objectsAPI.uploadChunk(
          bucketKey, objectKey,
          length, range, sessionId,
          readStream, {},
          {autoRefresh: false}, token)
      }

      return {
        chunkIndex: chunkIdx,
        run
      }
    })

    let progress = 0

    // runs asynchronously in parallel the upload tasks
    // number of simultaneous uploads is defined by
    // opts.concurrentUploads
    eachLimit(uploadTasks, opts.concurrentUploads || 3,
      (task, callback) => {

        task.run().then((res) => {

          if (opts.onProgress) {

            progress += 100.0 / nbChunks

            opts.onProgress ({
              progress: Math.round(progress * 100) / 100,
              chunkIndex: task.chunkIndex
            })
          }

          callback ()

        }, (err) => {

          console.log('error')
          console.log(err)

          callback(err)
        })

    }, (err) => {

        if (err) {

          return reject(err)
        }

        return resolve({
          fileSize: file.size,
          bucketKey,
          objectKey,
          nbChunks
        })
    })
  })
}


问:
How to post a tweet using Codebird PHP from pop-up window
I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.

What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:

Here's my PHP:

```<code>function tweet($message,$image) {
    require_once('codebird.php');
    \Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
    $cb = \Codebird\Codebird::getInstance();
    session_start();

    if (! isset($_SESSION['oauth_token'])) {
      // get the request token
      $reply = $cb->oauth_requestToken([
        'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
      ]);

      // store the token
      $cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
      $_SESSION['oauth_token'] = $reply->oauth_token;
      $_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
      $_SESSION['oauth_verify'] = true;

      // redirect to auth website
      $auth_url = $cb->oauth_authorize();
      header('Location: ' . $auth_url);
      die();

    } elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
      // verify the token
      $cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
      unset($_SESSION['oauth_verify']);

      // get the access token
      $reply = $cb->oauth_accessToken([
        'oauth_verifier' => $_GET['oauth_verifier']
      ]);

      // store the token (which is different from the request token!)
      $_SESSION['oauth_token'] = $reply->oauth_token;
      $_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;

      // send to same URL, without oauth GET parameters
      header('Location: ' . basename(__FILE__));
      die();
    }

    // assign access token on each page load
    $cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $reply = $cb->media_upload(array(
        'media' => $image
    ));
    $mediaID = $reply->media_id_string;
    $params = array(
        'status' => $message,
        'media_ids' => $mediaID
    );
    $reply = $cb->statuses_update($params);
}

tweet("Tweet tweet","assets/tweet.jpg");
</code>```

And here's my Javascript/HTML:

```<code>function postTweet() {
  $.ajax({
    type: "POST",
    url: 'tweet.php',
    data:{action:'call_this'},
    success:function(html) {
      alert('Success!');
    }
  });
}
<button class="download-share" onclick="postTweet()">Download and Share</button>
</code>```

答:
First things first, you(codebird) are using the twitter API to post to twitter, which makes use of the statuses/update endpoint in the API. This call is a server to server call, ie from the server where your files are hosted to the twitter server.
https://dev.twitter.com/rest/reference/post/statuses/update

There are 2 possibilities i see for you to accomplish what you have in mind

-first would be to use twitters web intent system with which you can send the tweet as a query string which would bring up the popup provided you have included the twitter js files
https://dev.twitter.com/web/tweet-button/web-intent

-second if thats not really your style then you could try something like what @ceejayoz mentioned making a new window created by you recreating the necessary inputs as shown in the picture and follow the same procedure you have now

Now to your question, Since you have an image the web intent option will not work, but if its a link with an image( twitter cards ) then i think the twitter bots should be able to read through the page and show you a preview in the popup provided you have the right meta tags on the linked page

Body:
I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.

What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:

Here's my PHP:

function tweet($message,$image) {
    require_once('codebird.php');
    \Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
    $cb = \Codebird\Codebird::getInstance();
    session_start();

    if (! isset($_SESSION['oauth_token'])) {
      // get the request token
      $reply = $cb->oauth_requestToken([
        'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
      ]);

      // store the token
      $cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
      $_SESSION['oauth_token'] = $reply->oauth_token;
      $_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
      $_SESSION['oauth_verify'] = true;

      // redirect to auth website
      $auth_url = $cb->oauth_authorize();
      header('Location: ' . $auth_url);
      die();

    } elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
      // verify the token
      $cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
      unset($_SESSION['oauth_verify']);

      // get the access token
      $reply = $cb->oauth_accessToken([
        'oauth_verifier' => $_GET['oauth_verifier']
      ]);

      // store the token (which is different from the request token!)
      $_SESSION['oauth_token'] = $reply->oauth_token;
      $_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;

      // send to same URL, without oauth GET parameters
      header('Location: ' . basename(__FILE__));
      die();
    }

    // assign access token on each page load
    $cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $reply = $cb->media_upload(array(
        'media' => $image
    ));
    $mediaID = $reply->media_id_string;
    $params = array(
        'status' => $message,
        'media_ids' => $mediaID
    );
    $reply = $cb->statuses_update($params);
}

tweet("Tweet tweet","assets/tweet.jpg");

And here's my Javascript/HTML:

function postTweet() {
  $.ajax({
    type: "POST",
    url: 'tweet.php',
    data:{action:'call_this'},
    success:function(html) {
      alert('Success!');
    }
  });
}
<button class="download-share" onclick="postTweet()">Download and Share</button>


问:
Jar File only working on my computer
I have code to run a simple runtime test on how long it takes to run a simple file, once it completes that I output the results to a file in the public users folder. It works on my computer but not on anyone other. This is my code</p>

```<code>import java.awt.List;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import javax.swing.*;
    public class Speed {
    public static void main(String[] args) {

        final long length=100000000;
        List merh = new List();
        File filename = new File("C:\\Users\\Public\\filename.txt ");
        final long startTime = System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
             merh.add( "Hereherehehrehrehrherh");
        }
        final long endTime = System.currentTimeMillis();

        System.out.println("Total execution time: " + (endTime - startTime)
);

        Writer writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(

                  new FileOutputStream(filename), "utf-8"));
            writer.write("Total execution time: " + (endTime - startTime));
        } catch (IOException ex) {
          // report
        } finally {
           try {writer.close();} catch (Exception ex) {/*ignore*/}
        }

     }

}
</code>```

答:
You are using an absolute pathname, which you should try to avoid. The reason it's failing is likely because the other computer you're using it on doesn't contain the directory C:\Users\Public\. Instead, you should use System.getProperty("user.home"). This line:

```<code>File filename = new File("C:\\Users\\Public\\filename.txt ");
</code>```

Would therefore become:

```<code>File filename = new File(System.getProperty("user.home") + "\\filename.txt");
</code>```

System Properties

Title: Jar File only working on my computer

Body:
I have code to run a simple runtime test on how long it takes to run a simple file, once it completes that I output the results to a file in the public users folder. It works on my computer but not on anyone other. This is my code

import java.awt.List;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import javax.swing.*;
    public class Speed {
    public static void main(String[] args) {

        final long length=100000000;
        List merh = new List();
        File filename = new File("C:\\Users\\Public\\filename.txt ");
        final long startTime = System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
             merh.add( "Hereherehehrehrehrherh");
        }
        final long endTime = System.currentTimeMillis();

        System.out.println("Total execution time: " + (endTime - startTime)
);

        Writer writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(

                  new FileOutputStream(filename), "utf-8"));
            writer.write("Total execution time: " + (endTime - startTime));
        } catch (IOException ex) {
          // report
        } finally {
           try {writer.close();} catch (Exception ex) {/*ignore*/}
        }

     }

}

Body:
You are using an absolute pathname, which you should try to avoid. The reason it's failing is likely because the other computer you're using it on doesn't contain the directory C:\Users\Public\. Instead, you should use System.getProperty("user.home"). This line:

File filename = new File("C:\\Users\\Public\\filename.txt ");

Would therefore become:

File filename = new File(System.getProperty("user.home") + "\\filename.txt");

System Properties


问:
Curious behaviour of std::string::operator[] in MSVC
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

```<code>t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);
</code>```

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?

答:
std::string is not an array. It is an object, whose interface loosely resembles an array (namely, provides operator[]). But that's when the similarity ends.

Even if we for a second assume that std::string is just a wrapper built on top of an ordinary array, then in order to obtain the one-past-the-end pointer for the stored sequence, you have to do something like &arg.second[0] + t.end, i.e. instead of going through the std::string interface first move into into the domain of ordinary pointers and use ordinary low-level pointer arithmetic.

However, even that assumption is not correct and doing something like &arg.second[0] + t.end is a recipe for disaster. std::string is not guaranteed to store its controlled sequence as an array. It is not guaranteed to be stored continuously, meaning that regardless of where your pointers point, you cannot assume that you'll be able to iterate from one to another by using pointer arithmetic.

If you want to use an std::string in some legacy pointer-based interface the only choice you have is to go through the std::string::c_str() method, which will generate a non-permanent array-based copy of the controlled sequence.

P.S. Note, BTW, that in the original C and C++ specifications it is illegal to use the &a[N] method to obtain the one-past-the-end pointer even for an ordinary built-in array. You always have to make sure that you are not using the [] operator with past-the-end index. The legal way to obtain the pointer has always been something like a + N or &a[0] + N, but not &a[N]. Recent changes legalized the &a[N] approach as well, but nevertheless originally it was not legal.

Body:
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?