答:
If you using ajax, follow below code

```<code><!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
 <span id = 'PHP_data'></span>
</body>

</html>

<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
  <script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
      message1 = "Hi "+message
       $('#PHP_data').html(message1);
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  }
  </script>
</code>```

If you are using form submit use below code

```<code><!DOCTYPE html>
<html>

<head>
</head>

<body>
  <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
  Enter message: <input type="text" id="message" name = "message">
  <input type="submit" value="submit" />
 <?php if(isset($_GET['message'])){
 echo "hi".$_GET['message'];
  die;
} ?>
 </form>
</body>

</html>
</code>```

Title: Access the php value on the same page using jquery and ajax

Body:
i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code

< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>     <
  script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  } <
  /script>

<!DOCTYPE html>

  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
  <?php echo "hi".$_GET['var_PHP_data'];?>

My php script is:

<?php
echo "hi".$_GET['var_PHP_data'];
?>

the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.

Body:
If you using ajax, follow below code

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
 <span id = 'PHP_data'></span>
</body>

</html>

<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
  <script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
      message1 = "Hi "+message
       $('#PHP_data').html(message1);
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  }
  </script>

If you are using form submit use below code

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
  Enter message: <input type="text" id="message" name = "message">
  <input type="submit" value="submit" />
 <?php if(isset($_GET['message'])){
 echo "hi".$_GET['message'];
  die;
} ?>
 </form>
</body>

</html>


来源: stackexchange

问:
Error just on host, not on my computer; String was not recognized as a valid DateTime
I am in bad situation. I have a program that it works very well in my computer but when I upload it on the host it gives me this error "String was not recognized as a valid DateTime." my program is on ASP.net C# visual studio 2015

Edit:
  both date's format on my computer and on the host are the same. like
  this:"mm/dd/yyyy"

would you please help me?
here is my code:
HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/mainMembers/frameMembers.Master" AutoEventWireup="true" CodeBehind="GMList.aspx.cs" Inherits="Federation.mainMembers.GMList" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainFrame" runat="server">
    <form id="gml" runat="server" method="post">
        <asp:Label ID="titr" runat="server" CssClass="shekaste" Text="title"></asp:Label>

        <asp:GridView ID="fedList" runat="server" AutoGenerateColumns="false" CssClass="parastoo" OnRowDataBound="MatchList_RowDataBound" >
            <Columns>

                <asp:BoundField HeaderText="a" DataField="birthday" />

                <asp:BoundField HeaderText="b" DataField="start_sport" />

                <asp:BoundField HeaderText="c" DataField="ToDate" />

            </Columns>
        </asp:GridView>

        </form>
</asp:Content>```
</div>
</div>
</p>

<ol start="2">
<li><p>C# code:</p>

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Globalization;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO;

namespace Federation.mainMembers
{

    public partial class GMList : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSG"].ConnectionString);
        //SqlConnection con = new SqlConnection(conStr);
        DataSet ds = new DataSet();
        //private string strSQL;
        private SqlCommand com;
        SqlDataAdapter sda;
        // DateTime dtime;
        DataTable dt = new DataTable();
        //DataTable dt1 = new DataTable();
        PersianCalendar pc = new PersianCalendar();
        //string memberID = "1111111112";
        string matchID = "";
        Boolean[] age2 = new Boolean[6];
        Boolean[] weight = new Boolean[9];
        //Int16 morshedi = 0;
        byte[] img1 = new byte[0];

        Int16 level;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["FID"] != null)
            {
                matchID = this.Session["FID"].ToString();
                //memberID = this.Session["VID"].ToString();
                //morshedi = Convert.ToInt16(this.Session["VMID"].ToString());

                //string s;

                if (!Page.IsPostBack)
                {

                    //********************************************************
                    dt.Rows.Clear();
                    con.Close();
                    sda = new SqlDataAdapter("select birthday,start_sport,ToDate   from general_members ", con);
                    con.Close();

                    con.Open();
                    dt.Rows.Clear();
                    sda.Fill(dt);

                    con.Close();
                    //string dds=dt.Rows[0]["ToDate"].ToString();
                    DataView dv1 = new DataView(dt);

                    fedList.DataSource = dv1;

                    fedList.DataBind();

                }
            }
            else
            {
                Response.Redirect("~/a.aspx");
            }

        }

        protected void MatchList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Find the value in the c04_oprogrs column. You'll have to use
                // some trial and error here to find the right control. The line
                // below may provide the desired value but I'm not entirely sure.

                TableCell statusCell1 = e.Row.Cells[0];
                TableCell statusCell2 = e.Row.Cells[1];
                TableCell statusCell3 = e.Row.Cells[2];

                string dstr = "";
                int year, month, day;
                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell1.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell2.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell2.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell2.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell2.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell3.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell3.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell3.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell3.Text = dstr;

            }
        }
    }
}
```

答:
I noticed that in the c# part of your code, you're using the Convert.ToDateTime(string) overload. If you're using that, then the string you passed is converted using the regional settings of the machine you run this code on. Thus, the most likely cause is that the regional settings of your local machine and the host machine are different.

There's two things you can try:

Change the regional settings on your machine to what it is on the host. Most likely the error will then appear on your local system too.

Try to use the overload Convert.ToDateTime(string, IFormatProvider). This will ensure that the conversion is always performed in the same way, regardless of your local settings.

ContentLicense: CC BY-SA 3.0

Body:
I am in bad situation. I have a program that it works very well in my computer but when I upload it on the host it gives me this error "String was not recognized as a valid DateTime." my program is on ASP.net C# visual studio 2015

Edit:
  both date's format on my computer and on the host are the same. like
  this:"mm/dd/yyyy"

would you please help me?
here is my code:
HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/mainMembers/frameMembers.Master" AutoEventWireup="true" CodeBehind="GMList.aspx.cs" Inherits="Federation.mainMembers.GMList" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainFrame" runat="server">
    <form id="gml" runat="server" method="post">
        <asp:Label ID="titr" runat="server" CssClass="shekaste" Text="title"></asp:Label>

        <asp:GridView ID="fedList" runat="server" AutoGenerateColumns="false" CssClass="parastoo" OnRowDataBound="MatchList_RowDataBound" >
            <Columns>

                <asp:BoundField HeaderText="a" DataField="birthday" />

                <asp:BoundField HeaderText="b" DataField="start_sport" />

                <asp:BoundField HeaderText="c" DataField="ToDate" />

            </Columns>
        </asp:GridView>

        </form>
</asp:Content>

C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Globalization;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO;

namespace Federation.mainMembers
{

    public partial class GMList : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSG"].ConnectionString);
        //SqlConnection con = new SqlConnection(conStr);
        DataSet ds = new DataSet();
        //private string strSQL;
        private SqlCommand com;
        SqlDataAdapter sda;
        // DateTime dtime;
        DataTable dt = new DataTable();
        //DataTable dt1 = new DataTable();
        PersianCalendar pc = new PersianCalendar();
        //string memberID = "1111111112";
        string matchID = "";
        Boolean[] age2 = new Boolean[6];
        Boolean[] weight = new Boolean[9];
        //Int16 morshedi = 0;
        byte[] img1 = new byte[0];

        Int16 level;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["FID"] != null)
            {
                matchID = this.Session["FID"].ToString();
                //memberID = this.Session["VID"].ToString();
                //morshedi = Convert.ToInt16(this.Session["VMID"].ToString());

                //string s;

                if (!Page.IsPostBack)
                {

                    //********************************************************
                    dt.Rows.Clear();
                    con.Close();
                    sda = new SqlDataAdapter("select birthday,start_sport,ToDate   from general_members ", con);
                    con.Close();

                    con.Open();
                    dt.Rows.Clear();
                    sda.Fill(dt);

                    con.Close();
                    //string dds=dt.Rows[0]["ToDate"].ToString();
                    DataView dv1 = new DataView(dt);

                    fedList.DataSource = dv1;

                    fedList.DataBind();

                }
            }
            else
            {
                Response.Redirect("~/a.aspx");
            }

        }

        protected void MatchList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Find the value in the c04_oprogrs column. You'll have to use
                // some trial and error here to find the right control. The line
                // below may provide the desired value but I'm not entirely sure.

                TableCell statusCell1 = e.Row.Cells[0];
                TableCell statusCell2 = e.Row.Cells[1];
                TableCell statusCell3 = e.Row.Cells[2];

                string dstr = "";
                int year, month, day;
                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell1.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell2.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell2.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell2.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell2.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell3.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell3.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell3.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell3.Text = dstr;

            }
        }
    }
}


问:
Find specific attribute and get its value
I have this:

```<code><button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>
</code>```

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

```<code>$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});
</code>```

答:
You can use [voice] selector to select your element and attr() method to get attribute value. After that use split() method to get your value. like following.

 $("button").click(function() {
    var ab = $("[voice]"),
        text = ab.attr('voice').split(',')[0];
    console.log(text);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p></code>```

Body:
I have this:

<button>Click</button>

My name is Donald.

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});

Body:
You can use [voice] selector to select your element and attr() method to get attribute value. After that use split() method to get your value. like following.

 $("button").click(function() {
    var ab = $("[voice]"),
        text = ab.attr('voice').split(',')[0];
    console.log(text);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>


问:
Solution for previewing user changes and allowing rollback/commit over a period of time
I have asked a few questions today as I try to think through to the solution of a problem.

We have a complex data structure where all of the various entities are tightly interconnected, with almost all entities heavily reliant/dependant upon entities of other types.

The project is a website (MVC3, .NET 4), and all of the logic is implemented using LINQ-to-SQL (2008) in the business layer.

What we need to do is have a user "lock" the system while they make their changes (there are other reasons for this which I won't go into here that are not database related). While this user is making their changes we want to be able to show them the original state of entities which they are updating, as well as a "preview" of the changes they have made. When finished, they need to be able to rollback/commit.

We have considered these options:

Holding open a transaction for the length of time a user takes to make multiple changes stinks, so that's out.

Holding a copy of all the data in memory (or cached to disk) is an option but there is heck of a lot of it, so seems unreasonable.

Maintaining a set of secondary tables, or attempting to use session state to store changes, but this is  complex and difficult to maintain.

Using two databases, flipping between them by connection string, and using T-SQL to manage replication, putting them back in sync after commit/rollback. I.e. switching on/off, forcing snapshot, reversing direction etc.

We're a bit stumped for a solution that is relatively easy to maintain. Any suggestions?

答:
Sounds like an ugly problem, and raises a whole lot of questions you won't be able to go into on SO. I got the following idea while reading your problem, and while it "smells" as bad as the others you list, it may help you work up an eventual solution.

First, have some kind of locking system, as described by @user580122, to flag/record the fact that one of these transactions is going on. (Be sure to include some kind of periodic automated check, to test for lost or abandoned transactions!)

Next, for every change you make to the database, log it somehow, either in the application or in a dedicated table somewhere. The idea is, given a copy of the database at state X, you could re-run the steps submitted by the user at any time.

Next up is figuring out how to use database snapshots. Read up on these in BOL; the general idea is you create a point-in-time snapshot of the database, do whatever you want with it, and eventually throw it away. (Only available in SQL 2005 and up, Enterprise edition only.)

So:

A user comes along and initiates one of these meta-transactions.

A flag is marked in the database showing what is going on. A new transaction cannot be started if one is already in process. (Again, check for lost transactions now and then!)

Every change made to the database is tracked and recorded in such a fashion that it could be repeated.

If the user decides to cancel the transaction, you just drop the snapshot, and nothing is changed.

If the user decides to keep the transaction, you drop the snapshot, and then immediately re-apply the logged changes to the "real" database. This should work, since your requirements imply that, while someone is working on one of these, no one else can touch the related parts of the database.

Yep, this sure smells, and it may not apply to well to your problem. Hopefully the ideas here help you work something out.

ContentLicense: CC BY-SA 2.5


问:
What does this script do (Windows CMD)
```<code>SET /P A=SPR
IF /I "%A:~,1%" EQU "d" (
    IF EXIST %1 (
        IF NOT EXIST %2 (
            COPY %1 %2
        )
    )
)
</code>```

答:
First, I suggest to open a command prompt window and run the following commands:

set /?

if /?

copy /?

call /? ... explains %1 and %2.

For each command the help is output which you should read from top to bottom.

This small batch file first prompts the batch file user for a string with prompt text SPR. The string entered by the user is assigned to environment variable A if the user enters anything at all as expected by this batch file.

Next a case-insensitive string comparison is done to check if the first character of the string entered by the user is d or D.

It would be much better to use comparison operator == instead of EQU in this case. == always makes a string comparison while EQU first tries to compare integers and if that fails because it is not possible to convert both comparison arguments to signed 32-bit integers, a string comparison is done. The second argument d is not a signed 32-bit integer.

The batch file must be started with two arguments being in this case two file names without or with wildcards. I suppose the batch file expects two file names without or with path without wildcards.

If the first condition is true, the batch file checks next if source file with name passed to batch file as first argument exists and next if target file passed to batch file as second argument does not exist. The source file is copied to target file if those 2 conditions are true.

More fail safe would be:

```<code>SET "Input=?"
SET /P "Input=SPR: "
IF /I "%Input:~0,1%" == "d" (
    IF "%~1" == "" GOTO :EOF
    IF "%~2" == "" GOTO :EOF
    IF EXIST "%~1" IF NOT EXIST "%~2" COPY "%~1" "%~2"
)
</code>```

The environment variable Input is now predefined with ? as string. So when the user just hits RETURN or ENTER without entering anything at all, the environment variable Input is nevertheless defined with ? as string and next command IF works, but of course the condition is in this case false.

The IF condition as is results in an exit of batch execution because of an syntax error only when the first entered character is ". In all other cases the IF condition works now and runs a case-insensitive string comparison.

The improved batch file checks next if the batch file was really started with two argument strings as expected and exit the batch file with a jump to predefined label for End Of File if either first or second argument is an empty string (or a string consisting only of one or two double quotes).

Title: What does this script do (Windows CMD)

Body:
First, I suggest to open a command prompt window and run the following commands:

set /?

if /?

copy /?

call /? ... explains %1 and %2.

For each command the help is output which you should read from top to bottom.

This small batch file first prompts the batch file user for a string with prompt text SPR. The string entered by the user is assigned to environment variable A if the user enters anything at all as expected by this batch file.

Next a case-insensitive string comparison is done to check if the first character of the string entered by the user is d or D.

It would be much better to use comparison operator == instead of EQU in this case. == always makes a string comparison while EQU first tries to compare integers and if that fails because it is not possible to convert both comparison arguments to signed 32-bit integers, a string comparison is done. The second argument d is not a signed 32-bit integer.

The batch file must be started with two arguments being in this case two file names without or with wildcards. I suppose the batch file expects two file names without or with path without wildcards.

If the first condition is true, the batch file checks next if source file with name passed to batch file as first argument exists and next if target file passed to batch file as second argument does not exist. The source file is copied to target file if those 2 conditions are true.

More fail safe would be:

SET "Input=?"
SET /P "Input=SPR: "
IF /I "%Input:~0,1%" == "d" (
    IF "%~1" == "" GOTO :EOF
    IF "%~2" == "" GOTO :EOF
    IF EXIST "%~1" IF NOT EXIST "%~2" COPY "%~1" "%~2"
)

The environment variable Input is now predefined with ? as string. So when the user just hits RETURN or ENTER without entering anything at all, the environment variable Input is nevertheless defined with ? as string and next command IF works, but of course the condition is in this case false.

The IF condition as is results in an exit of batch execution because of an syntax error only when the first entered character is ". In all other cases the IF condition works now and runs a case-insensitive string comparison.

The improved batch file checks next if the batch file was really started with two argument strings as expected and exit the batch file with a jump to predefined label for End Of File if either first or second argument is an empty string (or a string consisting only of one or two double quotes).


答:
try like this

```<code>$(document).ready(function(){
    $("button").on('click', function() {
    var ab = $(document).find("[voice]").attr('voice');
    console.log(ab);
    });
});
</code>```

play here if you want https://jsfiddle.net/up9ub1uh/

and it's better to use data-voice instead just voice attribute.

Title: Find specific attribute and get its value

Body:
try like this

$(document).ready(function(){
    $("button").on('click', function() {
    var ab = $(document).find("[voice]").attr('voice');
    console.log(ab);
    });
});

play here if you want https://jsfiddle.net/up9ub1uh/

and it's better to use data-voice instead just voice attribute.


问:
Should I commit or rollback a read transaction?
I have a read query that I execute within a transaction so that I can specify the isolation level.  Once the query is complete, what should I do?

Commit the transaction

Rollback the transaction

Do nothing (which will cause the transaction to be rolled back at the end of the using block)

What are the implications of doing each?

```<code>using (IDbConnection connection = ConnectionFactory.CreateConnection())
{
    using (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
    {
        using (IDbCommand command = connection.CreateCommand())
        {
            command.Transaction = transaction;
            command.CommandText = "SELECT * FROM SomeTable";
            using (IDataReader reader = command.ExecuteReader())
            {
                // Read the results
            }
        }

        // To commit, or not to commit?
    }
}
</code>```

EDIT: The question is not if a transaction should be used or if there are other ways to set the transaction level.  The question is if it makes any difference that a transaction that does not modify anything is committed or rolled back.  Is there a performance difference?  Does it affect other connections?  Any other differences?

答:
If you set AutoCommit false, then YES.

In an experiment with JDBC(Postgresql driver), I found that if select query breaks(because of timeout), then you can not initiate new select query unless you rollback.

OwnerDisplayName: Stefan Moser

Body:
I have a read query that I execute within a transaction so that I can specify the isolation level.  Once the query is complete, what should I do?

Commit the transaction

Rollback the transaction

Do nothing (which will cause the transaction to be rolled back at the end of the using block)

What are the implications of doing each?

using (IDbConnection connection = ConnectionFactory.CreateConnection())
{
    using (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
    {
        using (IDbCommand command = connection.CreateCommand())
        {
            command.Transaction = transaction;
            command.CommandText = "SELECT * FROM SomeTable";
            using (IDataReader reader = command.ExecuteReader())
            {
                // Read the results
            }
        }

        // To commit, or not to commit?
    }
}

EDIT: The question is not if a transaction should be used or if there are other ways to set the transaction level.  The question is if it makes any difference that a transaction that does not modify anything is committed or rolled back.  Is there a performance difference?  Does it affect other connections?  Any other differences?

LastEditorDisplayName: Stefan Moser

ContentLicense: CC BY-SA 4.0


问:
using bolt cms for single page app
I want to use bolt as a headless cms. My plan is to create a template based on vue.js and load the content utilizing the bolt plugin jsonAPI.
But I'm struggling with the theme and config settings.
I want to disable all routing in the CMS and return only a static html with css and js files.</p>

答:
I think your problem could be solved by the following alternative solution :

Use different domain

Put your vue SPA app in yourdomain.com and put your bolt as RESTAPI provider in subdomain.yourdomain.com. Since it's a subdomain, you would not face any CORST problem, and you can follow common tutorial how to setup bolt cms and how to build vuejs SPA.

Use vuejs SPA in bolt cms template

Assume you develop vuejs SPA using webpack, you have to setup asset public path as bolt template location, the configuration file is in your-vue-directory/config/index.js

```<code>module.exports = {
  build: {
    assetsPublicPath: '/theme/your-theme/',
    ......
  },
}
</code>```

Then after finish build the app, you can copy your build files from your-vue-directory/dist into your-bolt-directory/public/theme/your-theme

But using this solution, if you're using vue-router, i think you cannot use 'history'mode since all of the routing will be handled by bolt cms. The only possible router-mode is 'hash'.

Title: using bolt cms for single page app

Body:
I think your problem could be solved by the following alternative solution :

Use different domain

Put your vue SPA app in yourdomain.com and put your bolt as RESTAPI provider in subdomain.yourdomain.com. Since it's a subdomain, you would not face any CORST problem, and you can follow common tutorial how to setup bolt cms and how to build vuejs SPA.

Use vuejs SPA in bolt cms template

Assume you develop vuejs SPA using webpack, you have to setup asset public path as bolt template location, the configuration file is in your-vue-directory/config/index.js

module.exports = {
  build: {
    assetsPublicPath: '/theme/your-theme/',
    ......
  },
}

Then after finish build the app, you can copy your build files from your-vue-directory/dist into your-bolt-directory/public/theme/your-theme

But using this solution, if you're using vue-router, i think you cannot use 'history'mode since all of the routing will be handled by bolt cms. The only possible router-mode is 'hash'.


问:
break and return in ruby, how do you use them?
I just asked a question about return and it seems to do the same thing as break. How do you use return, and how do you use break, such as in the actual code that you write to solve the problems that can use these constructs.

I can't really post examples because I don't know how to use these so they wouldn't make much sense.

答:
One more example could be if you have two loops in a single method and if you want to come out of the first loop and continue to the second loop use break in the first loop or vice versa:</p>

```<code>def testing(method)
x=1
  10.times do
    if(x == 2)
     break if method == "break"
    end
   x+=1
  end
  10.times do
   if(x == 5)
     return if method == "return"
   end
  x+=1
  end
end
</code>```

Body:
One more example could be if you have two loops in a single method and if you want to come out of the first loop and continue to the second loop use break in the first loop or vice versa:

def testing(method)
x=1
  10.times do
    if(x == 2)
     break if method == "break"
    end
   x+=1
  end
  10.times do
   if(x == 5)
     return if method == "return"
   end
  x+=1
  end
end


问:
What is the
 character?
What's the meaning of this char?</p>

答:
This is the ASCII format.

Please consider that:

Some data (like URLs) can be sent over the Internet using the ASCII character-set.
  Since data often contain characters outside the ASCII set, so it has
  to be converted into a valid ASCII format.

To find it yourself, you can visit https://en.wikipedia.org/wiki/ASCII, there you can find big tables of characters. The one you are looking is in Control Characters table.

Digging to table you can find

Oct    Dec    Hex    Name
 012   10      0A     Line Feed

In the html file you can use Dec and Hex representation of charters

The Dec is represented with

The Hex is represented with &#x0A (or you can omit the leading zero &#xA)

There is a good converter at https://r12a.github.io/apps/conversion/ .

Title:
What is the
 character?

Body: What's the meaning of this char?

Body:
This is the ASCII format.

Please consider that:

Some data (like URLs) can be sent over the Internet using the ASCII character-set.
  Since data often contain characters outside the ASCII set, so it has
  to be converted into a valid ASCII format.

To find it yourself, you can visit https://en.wikipedia.org/wiki/ASCII, there you can find big tables of characters. The one you are looking is in Control Characters table.

Digging to table you can find

Oct    Dec    Hex    Name
 012   10      0A     Line Feed

In the html file you can use Dec and Hex representation of charters

The Dec is represented with &#10;

The Hex is represented with &#x0A (or you can omit the leading zero &#xA)

There is a good converter at https://r12a.github.io/apps/conversion/ .


答:
Try this.

$(document).ready(function(){
    $("button").click(function() {
    var ab = $("p").attr('voice');
    console.log(ab);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p></code>```

Body:
Try this.

$(document).ready(function(){
    $("button").click(function() {
    var ab = $("p").attr('voice');
    console.log(ab);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>


问:
Function in SQL Server 2008 similar to GREATEST in mysql?
I want to find the maximum value of multiple columns.

MySQL supports the GREATEST function but SQL Server doesn't.

Is there any function similar to this in SQL Server 2008?

答: Try using TOP instead or MAX.

Body: Try using TOP instead or MAX.


问:
Keystrokes In Applescript
I'm trying to run an applescript application on Mac OSX that automatically takes a picture with photobooth.  It isn't working.  The keystroke for taking a picture is "command" and "return".

Here is my script so far:

```<code>tell application "Photo Booth"
    activate
end tell
tell application "System Events"
    delay 3
    keystroke "return" using command down
end tell
</code>```

答:
tell application "Photo Booth"

activate

end tell

tell application "System Events"

    delay 3

    keystroke return --does not need the command

end tell

Title: Keystrokes In Applescript

Body:
I'm trying to run an applescript application on Mac OSX that automatically takes a picture with photobooth.  It isn't working.  The keystroke for taking a picture is "command" and "return".

Here is my script so far:

tell application "Photo Booth"
    activate
end tell
tell application "System Events"
    delay 3
    keystroke "return" using command down
end tell


问:
How to use x:Object and when?
When passing arguments by the markup extension x:Arguments to non default constructors as specified by the docs, I can see the use of concrete data types such as x:Int32 or x:String, but what's the use case of x:Object? And what's more, to use it, what should be put between the tag? <x:Object> ??? </x:Object>

In the case of integer or string, it is natural to think them as an variable assignment and the variables then get passed to the constructors. But in the case of Object, such an variable normally is constructed by another user defined class, so how to specify what class you want to create?

答:
x:Object

The x:Object primitive corresponds to Object. This primitive is not typically used in application markup but might be useful for some scenarios such as checking assignability in a XAML type system. You can use as Argument.

Take a look at the Xamarin documentation on Resource Dictionaries for a full explanation on how to use the x:Key attribute of your resources.

Each resource has a key that is specified using the x:Key attribute,
  which gives it a descriptive key in the ResourceDictionary.

You can use it like below:

```<code><local:MockFactory >
     <x:Arguments>
         <x:Array Type="{x:Type x:Object}">
             <x:String>Foo</x:String>
             <x:String>Bar</x:String>
         </x:Array>
     </x:Arguments>
</local:MockFactory>
</code>```

you can find a related example here

Title: How to use x:Object and when?

Body:
x:Object

The x:Object primitive corresponds to Object. This primitive is not typically used in application markup but might be useful for some scenarios such as checking assignability in a XAML type system. You can use as Argument.

Take a look at the Xamarin documentation on Resource Dictionaries for a full explanation on how to use the x:Key attribute of your resources.

Each resource has a key that is specified using the x:Key attribute,
  which gives it a descriptive key in the ResourceDictionary.

You can use it like below:

<local:MockFactory >
     <x:Arguments>
         <x:Array Type="{x:Type x:Object}">
             <x:String>Foo</x:String>
             <x:String>Bar</x:String>
         </x:Array>
     </x:Arguments>
</local:MockFactory>

you can find a related example here


问:
How to print ajax response to span class
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

```<code><span class="selected_item">0 available Slots</span>
<div class="form_item_dropdown">
    <div class="dropdown_wrapper">
        <li class="timeSlot" id="time1">
            <i class="icon fa fa-clock-o" aria-hidden="true">
            </i>
            <span class="item_title">10am - 4pm (value comes through Ajax)</span>
        </li>
    </div>
</div>
</code>```

Ajax code :

```<code>   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });
</code>```

Here is the response :

```<code>{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}
</code>```

答:
Just change the content of foreach loop.  </p>

```<code>var divContent = '';
$.each(data,function(index,subcatObj){
    divContent += '<li class="timeSlot" id="time'+subcatObj.id+'"><i class="icon fa fa-clock-o" aria-hidden="true"></i><span class="item_title">'+subcatObj.break_time+'</span></li>';
});
$(".dropdown_wrapper").append(divContent);
</code>```

Body:
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

0 available Slots

            10am - 4pm (value comes through Ajax)

Ajax code :

   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });

Here is the response :

{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}

Body:
Just change the content of foreach loop.

var divContent = '';
$.each(data,function(index,subcatObj){
    divContent += '<li class="timeSlot" id="time'+subcatObj.id+'"><i class="icon fa fa-clock-o" aria-hidden="true"></i><span class="item_title">'+subcatObj.break_time+'</span></li>';
});
$(".dropdown_wrapper").append(divContent);


问:
How can a create a log file to log every steps in python?
I am running a python script and I want to log each steps of the python program.

for example, lets say I have a program

```<code>def main()
    if do:
       do the work
       if yes:
          do the work
          for list os.listdir(dir):
              sys.system("python " + dirOfPython + " " + dirOflists)
</code>```

I want to log where my program is.. and what they are currently doing.

In my log I want something like

```<code>Inside of main()
inside of if do:
doing work
inside of if yes:
doing work
inside of for each files/dirs calling list
calling sys.system python
executing python with give dir path
</code>```

not exactly what is above.. but some sort of log to see what the program is doing and if it fails this log will contain where if failed log with error message

I just want a formal log file

答:
I think in program you need to know what is executing currently and what is the flow of the program and where it is breaking, this is where logs come into picture. For this you can use this pip library function-logger.

(INSTALLING) Install it with the following command:

```<code>pip install function-logger
</code>```

(IMPORT STATEMENT) Inside your code import this library

```<code>from function_logger import function_logger
</code>```

(USAGE) how to use
Use it like the decorator on any function for which you want to see logs ex:

```<code>@function_logger(logger)
def log_function(name=None, age=None):
    logger.debug("Inside log function")
    return dict(bmi=19)
</code>```

Output:

```<code>Inside Function log_function with parameters: (),{'name': 'hello', 'age': 23'}
Inside log function
Function: log_function returns 19
</code>```

Body:
I am running a python script and I want to log each steps of the python program.

for example, lets say I have a program

def main()
    if do:
       do the work
       if yes:
          do the work
          for list os.listdir(dir):
              sys.system("python " + dirOfPython + " " + dirOflists)

I want to log where my program is.. and what they are currently doing.

In my log I want something like

Inside of main()
inside of if do:
doing work
inside of if yes:
doing work
inside of for each files/dirs calling list
calling sys.system python
executing python with give dir path

not exactly what is above.. but some sort of log to see what the program is doing and if it fails this log will contain where if failed log with error message

I just want a formal log file

Body:
I think in program you need to know what is executing currently and what is the flow of the program and where it is breaking, this is where logs come into picture. For this you can use this pip library function-logger.

(INSTALLING) Install it with the following command:

pip install function-logger

(IMPORT STATEMENT) Inside your code import this library

from function_logger import function_logger

(USAGE) how to use
Use it like the decorator on any function for which you want to see logs ex:

@function_logger(logger)
def log_function(name=None, age=None):
    logger.debug("Inside log function")
    return dict(bmi=19)

Output:

Inside Function log_function with parameters: (),{'name': 'hello', 'age': 23'}
Inside log function
Function: log_function returns 19


问:
How to change the Auto Growth size? MS SQL Server 2005
In MS Sql server 2005, by default 1MB Auto Growth is there, How can i change it to whatever i need.?

Thanx,
Ambanna

答:
In SQL Server Management Studio, right click on the database.

Go to Properties.

Then go to the Files section.

Click on either the data or log autogrowth column (Click the ...)

Then change it to whatever you want it to be.

OwnerDisplayName: Ambanna

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Bravax


问:
Java JDBC thows com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException for \'Test1\' value
I have below table:
dummy_tbl

```<code>  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|
</code>```

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

```<code> select * from dummy_tbl where name like \'Test1\';
</code>```

But same query when I tried from code using JDBC statement it's throwing below error:

```<code> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1
</code>```

Code snipped from code:

```<code>  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);
</code>```

答:
try this once

select * from dummy_tbl where name like \\'Test\\';

Body:
I have below table:
dummy_tbl

  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

 select * from dummy_tbl where name like \'Test1\';

But same query when I tried from code using JDBC statement it's throwing below error:

 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1

Code snipped from code:

  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);


问:
Promise flattening fails - why?
```<code>const simplePromise = i => {
    return new Promise(function(resolve, reject) {
        console.log(i);
        setTimeout(function(){
            resolve();
        }, 2000);
    });
}

var anchor = simplePromise(0);
for (var i=1; i<4; i++) {
    anchor = anchor.then(_ => simplePromise(i));
}
</code>```

prints:

```<code>0
4
4
4
4
</code>```

instead of:

```<code>0
1
2
3
4
</code>```

1. Can someone explain why? and 2. tell me how to achieve this?

I can see that the first promise is executed (i=0), then the loop runs and then the value of i(=4) gets passed to the next promise. Shouldn't this be solved by having a function inside then (_ => simplePromise(i)) ?

答:
It's happened due you use var. Try to change var to let and that fix your problem.

UPDATE

That problem more clearly explained at this article and this (scroll to section Difference Details -> Closure in Loop) and great explanation of let key word

EXPLANATION

Let take that piece of code:

for (var i = 0; i < 5; ++i) {
  setTimeout(function () {
    console.log(i); // output '5' 5 times
  }, 100);
}```

In that example each iteration create function with closure on variable i, which will be executed in the future. Problem is var declare variable which

...is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block.

i.e. all of the created functions will create closure to the same variable. And when the execution time comes i === 5. And All of the function will print the same value.

How let solve that problem...

let in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration, so it can be used to avoid issue with closures.

Title: Promise flattening fails - why?

Body:
const simplePromise = i => {
    return new Promise(function(resolve, reject) {
        console.log(i);
        setTimeout(function(){
            resolve();
        }, 2000);
    });
}

var anchor = simplePromise(0);
for (var i=1; i<4; i++) {
    anchor = anchor.then(_ => simplePromise(i));
}

prints:

0
4
4
4
4

instead of:

0
1
2
3
4

1. Can someone explain why? and 2. tell me how to achieve this?

I can see that the first promise is executed (i=0), then the loop runs and then the value of i(=4) gets passed to the next promise. Shouldn't this be solved by having a function inside then (_ => simplePromise(i)) ?

Body:
It's happened due you use var. Try to change var to let and that fix your problem.

UPDATE

That problem more clearly explained at this article and this (scroll to section Difference Details -> Closure in Loop) and great explanation of let key word

EXPLANATION

Let take that piece of code:

for (var i = 0; i < 5; ++i) {
  setTimeout(function () {
    console.log(i); // output '5' 5 times
  }, 100);
}

In that example each iteration create function with closure on variable i, which will be executed in the future. Problem is var declare variable which

...is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block.

i.e. all of the created functions will create closure to the same variable. And when the execution time comes i === 5. And All of the function will print the same value.

How let solve that problem...

let in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration, so it can be used to avoid issue with closures.


问:
exiting recursive loop - python
I am writing a small collision check function. If 'is_collision" function return 'True' the function 'extend_until' should stop executing all the recursive functions and return the start point of the corresponding loop. I am not quite sure how this should be executed.

I have a discretization resolution of 1.0 unit along the length and hence starting initial if condition in 'extend until' function.

```<code>def is_collision(query):
    print "Collision occurred"
    return True

def extend_until(start, goal):
    if goal-start <= 1.0:
        if is_collision(goal):
            # if YES all recursion should stop and return.
            return start
    else:
        midpoint = (start+goal)/2
        extend_until(start, midpoint)
        extend_until(midpoint, goal)

    return goal

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print new_configuration
</code>```

答:
Is this good enough?

```<code>def is_collision(start, goal):
    if goal-start <= 1.0:
        print('Collision occurred')
        return True
    return False

def extend_until(start, goal):
    print("Start is: "+str(start))
    if is_collision(start, goal):
        # if YES all recursion should stop and return.
        return goal-start
    else:
        #midpoint = (start+goal)/2
        #extend_until(start, midpoint)
        start = start + 1
        return extend_until(start, goal)

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print('New Configuration is: '+ str(new_configuration))
</code>```

Output:-

```<code>Start is: 0
Start is: 1
Start is: 2
Start is: 3
Collision occurred
New Configuration is: 1
</code>```

Title: exiting recursive loop - python

Body:
I am writing a small collision check function. If 'is_collision" function return 'True' the function 'extend_until' should stop executing all the recursive functions and return the start point of the corresponding loop. I am not quite sure how this should be executed.

I have a discretization resolution of 1.0 unit along the length and hence starting initial if condition in 'extend until' function.

def is_collision(query):
    print "Collision occurred"
    return True

def extend_until(start, goal):
    if goal-start <= 1.0:
        if is_collision(goal):
            # if YES all recursion should stop and return.
            return start
    else:
        midpoint = (start+goal)/2
        extend_until(start, midpoint)
        extend_until(midpoint, goal)

    return goal

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print new_configuration

Body:
Is this good enough?

def is_collision(start, goal):
    if goal-start <= 1.0:
        print('Collision occurred')
        return True
    return False

def extend_until(start, goal):
    print("Start is: "+str(start))
    if is_collision(start, goal):
        # if YES all recursion should stop and return.
        return goal-start
    else:
        #midpoint = (start+goal)/2
        #extend_until(start, midpoint)
        start = start + 1
        return extend_until(start, goal)

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print('New Configuration is: '+ str(new_configuration))

Output:-

Start is: 0
Start is: 1
Start is: 2
Start is: 3
Collision occurred
New Configuration is: 1


问:
Why compiler didn't use same object reference for a static expression tree?
As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

To clarify the question please see the example:

```<code>static void Main(string[] args)
{
    Test(p => true);//2637164
    Test(p => true);//3888474
    Test("true");//-292522067
    Test("true");//-292522067
    Console.ReadKey();
}

public static void Test(Expression<Func<string,bool>> exp)
{
    Console.WriteLine(exp.GetHashCode());
}

public static void Test(string str)
{
    Console.WriteLine(str.GetHashCode());
}
</code>```

答:
As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

The spec says that the compiler is permitted but not required to intern identical lambdas.

String literals are interned by the runtime for free; there's no cost to the compiler developer to do it.

The reason why I didn't intern expression trees is because every day we spent working on pointless unnecessary "optimizations" for unrealistic scenarios that actually save no valuable resource is a day that Visual Studio would have slipped its schedule. We spent that time on actual optimizations.

Body:
As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

To clarify the question please see the example:

static void Main(string[] args)
{
    Test(p => true);//2637164
    Test(p => true);//3888474
    Test("true");//-292522067
    Test("true");//-292522067
    Console.ReadKey();
}

public static void Test(Expression<Func<string,bool>> exp)
{
    Console.WriteLine(exp.GetHashCode());
}

public static void Test(string str)
{
    Console.WriteLine(str.GetHashCode());
}


问:
Vim distro with both python support and xterm_clipboard
I'm using Vim in combination with mono for ASP.NET development. The OmniSharp plugin requires python 2 support.

This suggest the vim.nox-py2 distribution. But vim.nox-py2 does not include the system clipboard support (-xterm_clipboard), which I find quite essential.

The vim.gtk3 distribution does include support for the system clipboard (+xterm_clipboard) but it doesn't have python 2 support.

Is there a way to have Vim support both python2 and the system clipboard in Ubuntu 16.04?

答:
+xterm_clipboard doesn't provide "support for the system clipboard"; it's +clipboard that does. You get that feature with any vim-gtk*/vim-gnome* package.

$ apt list vim gives you a list of Vim packages. Among them you have these three packages that all satisfy your requirements:

vim-gnome-py2

vim-gtk-py2

vim-gtk3-py2


问:
Python :My generator is returning the passed list instead of a filtered output
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

```<code>def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()
</code>```

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.

答: Increment Counter my friend. You've incremented the count variable instead</p>

Body:
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.


答:
Not in SQL Server 2008 but GREATEST and LEAST functions are now available for SQL Server 2022 and cloud versions of SQL Server

For previous versions you can use the fact a sub query can access the columns from the outer query so you can add a sub query Selecting the max from a union of those.

```<code>SELECT *,
      (SELECT MAX(c) FROM (VALUES(number),(status)) T (c)) AS Greatest
FROM master..spt_values
</code>```

Or for SQL Server 2000/2005

```<code>SELECT *,
      (SELECT MAX(c) FROM
                    (SELECT number AS c
                     UNION ALL
                     SELECT status) T) AS GreatestNumberOrStatus
FROM master..spt_values
</code>```

Title: Function in SQL Server 2008 similar to GREATEST in mysql?

Body:
I want to find the maximum value of multiple columns.

MySQL supports the GREATEST function but SQL Server doesn't.

Is there any function similar to this in SQL Server 2008?

Body:
Not in SQL Server 2008 but GREATEST and LEAST functions are now available for SQL Server 2022 and cloud versions of SQL Server

For previous versions you can use the fact a sub query can access the columns from the outer query so you can add a sub query Selecting the max from a union of those.

SELECT *,
      (SELECT MAX(c) FROM (VALUES(number),(status)) T (c)) AS Greatest
FROM master..spt_values

Or for SQL Server 2000/2005

SELECT *,
      (SELECT MAX(c) FROM
                    (SELECT number AS c
                     UNION ALL
                     SELECT status) T) AS GreatestNumberOrStatus
FROM master..spt_values


问:
Do Statement that isn't working correctly
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!</p>

```<code>    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}
</code>```

答:
replace below line

```<code>while (swapflag = true); //this say that you are always setting swapflag to true
</code>```

with

```<code>while (swapflag);// check condition true or false
</code>```

Body:
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!

    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}

Body:
replace below line

while (swapflag = true); //this say that you are always setting swapflag to true

with

while (swapflag);// check condition true or false


问:
Find specific attribute and get its value
I have this:

```<code><button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>
</code>```

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

```<code>$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});
</code>```

答:
try with this code

$(document).ready(function() {
  $("button").click(function() {
    var ab = $(".intro").attr('voice');
    var new1 = ab.split(",");
    console.log(new1[0]);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p></code>```

Body:
I have this:

<button>Click</button>

My name is Donald.

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});

Body:
try with this code

$(document).ready(function() {
  $("button").click(function() {
    var ab = $(".intro").attr('voice');
    var new1 = ab.split(",");
    console.log(new1[0]);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>


问:
mysql cmdline client to return error to shell script
Is there a way to get the mysql cmdline client to abort as soon as it encounters an error, and to return a non-zero exit status to the controlling shell script.

Basically I want to be able to have a shell script like:

```<code>mysql -A --batch <<END_SQL
UPDATE table1...
UPDATE table2...
...
END_SQL
if [ $? -ne 0 ]
then
    # Error handling
fi
</code>```

With oracle I just had to put WHENEVER SQLERROR EXIT FAILURE at the top of the sql commands. Is there a mysql equivalent? Not found anything in google.

答:
By default, the mysql client already does exit when it encounters an error.

You can make the mysql client not exit when it encounters an error if you use the --force option.

```<code>$ echo "select * from nonexistanttable ; select now()" | mysql test
ERROR 1146 (42S02) at line 1: Table 'test.nonexistanttable' doesn't exist

$ echo $?
1
</code>```

Notice this does not return the result of now(). It exited first.

```<code>$ echo "select * from nonexistanttable ; select now()" | mysql --force test
ERROR 1146 (42S02) at line 1: Table 'test.nonexistanttable' doesn't exist
now()
2017-11-12 22:46:30

$ echo $?
0
</code>```

Ah, there it is.

This question is sort of the opposite of MySQL: ignore errors when importing?

It's not widely known that this is the behavior of the mysql client. The only clue would have been to read about the --force option in this manual page: https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html

Body:
Is there a way to get the mysql cmdline client to abort as soon as it encounters an error, and to return a non-zero exit status to the controlling shell script.

Basically I want to be able to have a shell script like:

mysql -A --batch <<END_SQL
UPDATE table1...
UPDATE table2...
...
END_SQL
if [ $? -ne 0 ]
then
    # Error handling
fi

With oracle I just had to put WHENEVER SQLERROR EXIT FAILURE at the top of the sql commands. Is there a mysql equivalent? Not found anything in google.

Body:
By default, the mysql client already does exit when it encounters an error.

You can make the mysql client not exit when it encounters an error if you use the --force option.

$ echo "select * from nonexistanttable ; select now()" | mysql test
ERROR 1146 (42S02) at line 1: Table 'test.nonexistanttable' doesn't exist

$ echo $?
1

Notice this does not return the result of now(). It exited first.

$ echo "select * from nonexistanttable ; select now()" | mysql --force test
ERROR 1146 (42S02) at line 1: Table 'test.nonexistanttable' doesn't exist
now()
2017-11-12 22:46:30

$ echo $?
0

Ah, there it is.

This question is sort of the opposite of MySQL: ignore errors when importing?

It's not widely known that this is the behavior of the mysql client. The only clue would have been to read about the --force option in this manual page: https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html


问:
How to get average score of K-Fold cross validation with sklearn
I apply decision tree with K-fold using sklearn and someone can help me to show the average score of it. Below is my code:</p>

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix,classification_report

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    print("classification_report_tree",
           classification_report(y_test,clf_tree.predict(X_test)))
</code>```

答:
You can try Precision_reacll_fscore_support metric from sklearn and then get average the results for each fold per class. I am assuming here that you need the scores average per class.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import GridSearchCV,cross_val_score

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

score_array =[]
for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    y_pred = clf.predict(X_test)
    score_array.append(precision_recall_fscore_support(y_test, y_pred, average=None))

avg_score = np.mean(score_array,axis=0)
print(avg_score)

#Output:
#[[  0.77302466   0.30042282]
# [  0.81755068   0.22192344]
# [  0.79063779   0.24414489]
# [ 57.          17.8       ]]
</code>```

Now to get precision of class 0, you can use avg_score[0][0]. The recall can be accessed by the second row (i.e. for class 0, it is avg_score[1][0]), while the fscore and support can be accessed from 3rd and 4th row respectively.

Body:
I apply decision tree with K-fold using sklearn and someone can help me to show the average score of it. Below is my code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix,classification_report

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    print("classification_report_tree",
           classification_report(y_test,clf_tree.predict(X_test)))

Body:
You can try Precision_reacll_fscore_support metric from sklearn and then get average the results for each fold per class. I am assuming here that you need the scores average per class.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import GridSearchCV,cross_val_score

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

score_array =[]
for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    y_pred = clf.predict(X_test)
    score_array.append(precision_recall_fscore_support(y_test, y_pred, average=None))

avg_score = np.mean(score_array,axis=0)
print(avg_score)

#Output:
#[[  0.77302466   0.30042282]
# [  0.81755068   0.22192344]
# [  0.79063779   0.24414489]
# [ 57.          17.8       ]]

Now to get precision of class 0, you can use avg_score[0][0]. The recall can be accessed by the second row (i.e. for class 0, it is avg_score[1][0]), while the fscore and support can be accessed from 3rd and 4th row respectively.


问:
Signing .NET assemblies
I'm trying to get a grasp of formal signing of .NET dlls/assemblies.

In particular

When and how to use private keys

Best practices for creation/control of private keys

What sort of modules need to be signed/ best practice for going about it

答:
See Using Strong Name Signatures for a very good article on signing.

If we are talking strong naming of assemblies then signing should be used to prevent a third party from "spoofing" your code. The strong name is part of your assembly so another assembly with the same name and a different signature is a different assembly.  This also prevents assemblies from being modified and re-signed (without the private key).

To be useful, the private key must be kept private. This is usually done through delayed signing and careful management of private key access.

You can also use Authenticode (to sign your strong named assemblies); this can add confidence about who the assembly is actually from.

Title: Signing .NET assemblies


问:
argument passing to echo in PHP
here are i am providing some examples of echo

Example 1

```<code>echo 'The sum is ', 1 + 2; //works fine
</code>```

Example 2

```<code>$x=true;
echo '$x is undefined value ' , ($x===true) ? 'NO' : 'Yes'; //Works fine
</code>```

Example 3

```<code>function f($arg){
  return $arg;
}

echo 'hello ' , f('buddy'); //Works fine
</code>```

Example 4 -

```<code>echo 'hello ' , if($a) { return "wowo"; } else { return "fine"; }; // generate parse error
</code>```

Here is the point that all example working fine but example 4 its generating parse error.

my questions is that -

1. language constructs can be used for echo arguments ?

2. If yes language constructs can be used, how can we use language constructs for echo arguments ?

3. Only functions that return strings can be passed to echo arguments ?

答:
Yes you can use language constructs to echo arguments or return values.
If else is a conditional statement which can be use to evaluate a value. using this you will be able to break the the logic into several pieces and evaluate the condition. the echo will work separately for an each statement. But if you return a value , it will be returned from function and not from the statement.
EX:

```<code>$value = "hello";
if($a) { $value.= "wowo"; } else { $value.= "fine"; }
echo $value;
</code>```

in the other hand ternary operator is an operator that takes three arguments and performs an operation .

Title: argument passing to echo in PHP

Body:
here are i am providing some examples of echo

Example 1

echo 'The sum is ', 1 + 2; //works fine

Example 2

$x=true;
echo '$x is undefined value ' , ($x===true) ? 'NO' : 'Yes'; //Works fine

Example 3

function f($arg){
  return $arg;
}

echo 'hello ' , f('buddy'); //Works fine

Example 4 -

echo 'hello ' , if($a) { return "wowo"; } else { return "fine"; }; // generate parse error

Here is the point that all example working fine but example 4 its generating parse error.

my questions is that -

1. language constructs can be used for echo arguments ?

2. If yes language constructs can be used, how can we use language constructs for echo arguments ?

3. Only functions that return strings can be passed to echo arguments ?

Body:
Yes you can use language constructs to echo arguments or return values.
If else is a conditional statement which can be use to evaluate a value. using this you will be able to break the the logic into several pieces and evaluate the condition. the echo will work separately for an each statement. But if you return a value , it will be returned from function and not from the statement.
EX:

$value = "hello";
if($a) { $value.= "wowo"; } else { $value.= "fine"; }
echo $value;

in the other hand ternary operator is an operator that takes three arguments and performs an operation .


问:
Downloading xls but in same column
The below code successfully downloads the xls file but the data are in the same column. how can I make it to the different column. The code seems working perfectly if I use csv but with xls it is not working like expected. I just want to make it like it appears on csv data.

Excel Data

CSV Data

```<code>    var data = [
      ['name1', 'city1', 'some other info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info']
    ];

    var csvContent = '';
    data.forEach(function(infoArray, index) {
      dataString = infoArray.join(" ");
      csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    var download = function(content, fileName, mimeType) {
      var a = document.createElement('a');
      mimeType = mimeType || 'application/octet-stream';

      if (navigator.msSaveBlob) {
        navigator.msSaveBlob(new Blob([content], {
          type: mimeType
        }), fileName);
      } else if (URL && 'download' in a) {
        a.href = URL.createObjectURL(new Blob([content], {
          type: mimeType
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        location.href = 'data:application/octet-stream,' + encodeURIComponent(content);
      }
    }

    download(csvContent, 'dowload.xls', 'text/xls;encoding:utf-8');
</code>```

credit link

Any help will be greatly appreciated.
Thanks.

答:
I found a script that creates xls file with super easy. Requires some dependent file such as

```<code><script type="text/javascript" src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script>
<script type="text/javascript" src="js/Blob.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>
</code>```

All those locally saved file blob.js and FileSaver.js can be found in here

Code

```<code>function datenum(v, date1904) {
    if(date1904) v+=1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
    for(var R = 0; R != data.length; ++R) {
        for(var C = 0; C != data[R].length; ++C) {
            if(range.s.r > R) range.s.r = R;
            if(range.s.c > C) range.s.c = C;
            if(range.e.r < R) range.e.r = R;
            if(range.e.c < C) range.e.c = C;
            var cell = {v: data[R][C] };
            if(cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

            if(typeof cell.v === 'number') cell.t = 'n';
            else if(typeof cell.v === 'boolean') cell.t = 'b';
            else if(cell.v instanceof Date) {
                cell.t = 'n'; cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            }
            else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

/* original data */

var excelData = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar",new Date("2014-02-19T14:30Z"), "0.3"], ["baz", null, "qux"]]

function createExcel(data) {

    var ws_name = "SheetJS";

    function Workbook() {
        if(!(this instanceof Workbook)) return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    }

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;
    var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'});

    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
    saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx")

}
</code>```

Title: Downloading xls but in same column

Body:
The below code successfully downloads the xls file but the data are in the same column. how can I make it to the different column. The code seems working perfectly if I use csv but with xls it is not working like expected. I just want to make it like it appears on csv data.

Excel Data

CSV Data

    var data = [
      ['name1', 'city1', 'some other info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info'],
      ['name2', 'city2', 'more info']
    ];

    var csvContent = '';
    data.forEach(function(infoArray, index) {
      dataString = infoArray.join(" ");
      csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    var download = function(content, fileName, mimeType) {
      var a = document.createElement('a');
      mimeType = mimeType || 'application/octet-stream';

      if (navigator.msSaveBlob) {
        navigator.msSaveBlob(new Blob([content], {
          type: mimeType
        }), fileName);
      } else if (URL && 'download' in a) {
        a.href = URL.createObjectURL(new Blob([content], {
          type: mimeType
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        location.href = 'data:application/octet-stream,' + encodeURIComponent(content);
      }
    }

    download(csvContent, 'dowload.xls', 'text/xls;encoding:utf-8');

credit link

Any help will be greatly appreciated.
Thanks.

Body:
I found a script that creates xls file with super easy. Requires some dependent file such as

<script type="text/javascript" src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script>
<script type="text/javascript" src="js/Blob.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>

All those locally saved file blob.js and FileSaver.js can be found in here

Code

function datenum(v, date1904) {
    if(date1904) v+=1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
    for(var R = 0; R != data.length; ++R) {
        for(var C = 0; C != data[R].length; ++C) {
            if(range.s.r > R) range.s.r = R;
            if(range.s.c > C) range.s.c = C;
            if(range.e.r < R) range.e.r = R;
            if(range.e.c < C) range.e.c = C;
            var cell = {v: data[R][C] };
            if(cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

            if(typeof cell.v === 'number') cell.t = 'n';
            else if(typeof cell.v === 'boolean') cell.t = 'b';
            else if(cell.v instanceof Date) {
                cell.t = 'n'; cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            }
            else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

/* original data */

var excelData = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar",new Date("2014-02-19T14:30Z"), "0.3"], ["baz", null, "qux"]]

function createExcel(data) {

    var ws_name = "SheetJS";

    function Workbook() {
        if(!(this instanceof Workbook)) return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    }

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;
    var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'});

    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
    saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx")

}


问:
Microsoft Azure run function after x minutes
I'm hosting my C# ASP.net website on azure currently, and i'm searching for a function that let's me execute code to change database entry's after x minutes after the request.

So i example:

User visits my website http://www.test.com/

Users leaves my site.

5 minutes later i change a variable in my database.

I already found something called WebJobs, but it's not the perfect fit.

答:
Per my understanding, you could log the action into Azure Storage Queue and specify the interval of time from now during which the message will be invisible as follows:

```<code>queue.AddMessage(new CloudQueueMessage("hello world"), initialVisibilityDelay:TimeSpan.FromMinutes(5));
</code>```

Then, you could work with WebJobs SDK to trigger your Azure queue storage. More details, you could refer to How to use Azure queue storage with the WebJobs SDK. Also, you could leverage Azure Functions Queue bindings to achieve the similar requirement, details you could follow here.

Moreover, you could also leverage the Scheduled messages from Azure Service Bus. Also, here is a similar issue, you could refer to the related code for sending a scheduled message. For processing the messages, you could refer to How to use Azure Service Bus with the WebJobs SDK or Azure Functions Service Bus bindings.

My website creates a temp e-mail account for the visitor. That email needs to be deleted after x minutes.

Per my understanding,  when you creating the temp e-mail account, you could record the create time and the expire time, and valid the temp account is valid or not when accessing your website. Then you could create a Recurring job (e.g. azure webjobs (TimerTrigger), or Hangfire,etc) to retrieve the expired accounts and delete them.

Body:
Per my understanding, you could log the action into Azure Storage Queue and specify the interval of time from now during which the message will be invisible as follows:

queue.AddMessage(new CloudQueueMessage("hello world"), initialVisibilityDelay:TimeSpan.FromMinutes(5));

Then, you could work with WebJobs SDK to trigger your Azure queue storage. More details, you could refer to How to use Azure queue storage with the WebJobs SDK. Also, you could leverage Azure Functions Queue bindings to achieve the similar requirement, details you could follow here.

Moreover, you could also leverage the Scheduled messages from Azure Service Bus. Also, here is a similar issue, you could refer to the related code for sending a scheduled message. For processing the messages, you could refer to How to use Azure Service Bus with the WebJobs SDK or Azure Functions Service Bus bindings.

My website creates a temp e-mail account for the visitor. That email needs to be deleted after x minutes.

Per my understanding,  when you creating the temp e-mail account, you could record the create time and the expire time, and valid the temp account is valid or not when accessing your website. Then you could create a Recurring job (e.g. azure webjobs (TimerTrigger), or Hangfire,etc) to retrieve the expired accounts and delete them.


问:
How not to compile casting into enum type in C++?
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

```<code>class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};
</code>```

This allows me to write the following code:

```<code>Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws
</code>```

My problem is that a compiler allows constructs such as:

```<code>Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws
</code>```

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

答:
No.  If you allow any cast to be used, as your last example does, then there will always be some cast that can be used to subvert your type.

The solution is to not be in the habit of using these casts and to very suspiciously consider any code that uses these casts indiscriminately.  View this type of casting as the nuclear bomb in your arsenal: it's important to have, but you always handle it with care and never want to deploy it more than rarely.

What warning options does your compiler have for casting?  What lint tools are you using which may detect this misuse of casts?

That said, it appears you really want to hide the inner Type so users are less tempted to even use it.  Realizing that, it's straight-forward to make that type name private, even while not preventing all cast misuse, by slightly tweaking your original:

```<code>struct Symmetry {
  enum {
    UNINITIALIZED,
    GENERAL, SYMMETRIC, HERMITIAN,
    SKEW_SYMMETRIC, SKEW_HERMITIAN
  };

private:
  typedef decltype(UNINITIALIZED) Hidden;
  Hidden _value;

public:
  Symmetry(Hidden value = UNINITIALIZED) : _value (value) {}
  Symmetry& operator=(Hidden value) { _value = value; return *this; }
  operator Hidden() const {
    if (_value == UNINITIALIZED) {
      throw std::logic_error("uninitialized Symmetry");
    }
    return _value;
  }

  bool initialized() const { return _value != UNINITIALIZED; }
  // required if you want to check for UNINITIALIZED without throwing in
  // the above conversion
};
</code>```

This is a complete implementation, no details omitted or unknown, or issues with initialization order.  The only caveat is decltype – with a pre-C++0x compiler, you'll have to use something implementation-specific or a library which wraps something implementation-specific.

And a smaller issue: change from runtime_error to logic_error, as using uninitialized values should be preventable beforehand and thus falls in the latter category.

Body:
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};

This allows me to write the following code:

Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws

My problem is that a compiler allows constructs such as:

Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

Body:
No.  If you allow any cast to be used, as your last example does, then there will always be some cast that can be used to subvert your type.

The solution is to not be in the habit of using these casts and to very suspiciously consider any code that uses these casts indiscriminately.  View this type of casting as the nuclear bomb in your arsenal: it's important to have, but you always handle it with care and never want to deploy it more than rarely.

What warning options does your compiler have for casting?  What lint tools are you using which may detect this misuse of casts?

That said, it appears you really want to hide the inner Type so users are less tempted to even use it.  Realizing that, it's straight-forward to make that type name private, even while not preventing all cast misuse, by slightly tweaking your original:

struct Symmetry {
  enum {
    UNINITIALIZED,
    GENERAL, SYMMETRIC, HERMITIAN,
    SKEW_SYMMETRIC, SKEW_HERMITIAN
  };

private:
  typedef decltype(UNINITIALIZED) Hidden;
  Hidden _value;

public:
  Symmetry(Hidden value = UNINITIALIZED) : _value (value) {}
  Symmetry& operator=(Hidden value) { _value = value; return *this; }
  operator Hidden() const {
    if (_value == UNINITIALIZED) {
      throw std::logic_error("uninitialized Symmetry");
    }
    return _value;
  }

  bool initialized() const { return _value != UNINITIALIZED; }
  // required if you want to check for UNINITIALIZED without throwing in
  // the above conversion
};

This is a complete implementation, no details omitted or unknown, or issues with initialization order.  The only caveat is decltype – with a pre-C++0x compiler, you'll have to use something implementation-specific or a library which wraps something implementation-specific.

And a smaller issue: change from runtime_error to logic_error, as using uninitialized values should be preventable beforehand and thus falls in the latter category.


问:
I want to remove staight line that shows in my blog page. It is only shows in firefox not in the chrome

I want to remove staight line that shows in my blog page. It is only shows in firefox not in the chrome. I don't know why it is showing in firefox?

I have added :

My website link

答:
remove width:1px in style.css line No: 5149

```<code>#main-content .container::before {
    position: absolute;
    top: 0;
    width: 0px;
    height: 100%;
    background-color: #e2e2e2;
    content: "";
}
</code>```

Body:
remove width:1px in style.css line No: 5149

#main-content .container::before {
    position: absolute;
    top: 0;
    width: 0px;
    height: 100%;
    background-color: #e2e2e2;
    content: "";
}


问:
Blank screens in my mobile device-Application
Till now my customer was using an old mobile with 4.4 android version. I didn't have any problems with my application.
Since my customer has changed the mobile in a new Galaxy j5 (2017) with Android version 7.0 Nougat. After that, the application in the android throw black screens in random places and it kicks out my application with message application doesn't respond. I cant find where is the problem and why this happens. Should I change my 'target Android version' in Android 7.0? Till now I'm using 'Use Compile Using SDK version.' Or new mobile is defective?

Here is my XML File

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="WiOrderAndroid.WiOrderAndroid" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="16" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application android:label="WiOrder" android:icon="@drawable/xs" android:theme="@style/CustomActionBarTheme"></application>
</manifest>
</code>```

答:
If you only change version from 4.4 to 7.0 my guess will be a new runtime permissions. Since Android 6.0 you required to ask for dangerous permission at runtime. You can find the list of that permissions here:

List of Android permissions normal permissions and dangerous permissions in API 23?

From your manifests, I can see that you use 2 dangerous permissions, which required a runtime permissions (WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE).

Since you are using Xamarin, you can use that snippet to handle all requesting process:

https://github.com/jamesmontemagno/PermissionsPlugin/blob/master/src/Plugin.Permissions.Android/PermissionsImplementation.cs

Body:
Till now my customer was using an old mobile with 4.4 android version. I didn't have any problems with my application.
Since my customer has changed the mobile in a new Galaxy j5 (2017) with Android version 7.0 Nougat. After that, the application in the android throw black screens in random places and it kicks out my application with message application doesn't respond. I cant find where is the problem and why this happens. Should I change my 'target Android version' in Android 7.0? Till now I'm using 'Use Compile Using SDK version.' Or new mobile is defective?

Here is my XML File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="WiOrderAndroid.WiOrderAndroid" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="16" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application android:label="WiOrder" android:icon="@drawable/xs" android:theme="@style/CustomActionBarTheme"></application>
</manifest>


问:
Python binary executable with MSAA hangs on exit
I'm using python comtypes to get access to IAccessible interface for MSAA (Microsoft Active Accessibility) usage. After that we create binary executable using pyinstaller, so the problem is that on specific platform - Windows XP x64 our executable hangs on exit. It hangs on WaitFotMultipleObjectsEx in ole32.dll after the process exit point is called - it hangs in system code not in our, or even pyinstaller boot loader. During investigation we located the problem - it is in creating many IAccessible objects (i.e. creating child tree) - if you do it proccess hangs. Wanna know if somebody else faced similar problem?

P.S. On other OSes it works fine.

答:
I'm not able to clearly understood the root reason of this issue currently. But the solution was found, even two.

First: to add an additional call to CoUninitialize function.
Don't know why it works as the comtypes calls CoUninitialize the same times as CoInitialize.

Second: to change CoInitializeEx flags, cause if COINIT_APARTMENTTHREADED is set (it is default value in comtypes if sys.coinit_flags is not defined) - process hangs! So i've choosen COINIT_SPEED_OVER_MEMORY and everything became fine! The easiest way to set it is to do following before importing comtypes:

```<code>import sys
sys.coinit_flags = 0x8 # COINIT_SPEED_OVER_MEMORY == 0x8
</code>```

Body:
I'm not able to clearly understood the root reason of this issue currently. But the solution was found, even two.

First: to add an additional call to CoUninitialize function.
Don't know why it works as the comtypes calls CoUninitialize the same times as CoInitialize.

Second: to change CoInitializeEx flags, cause if COINIT_APARTMENTTHREADED is set (it is default value in comtypes if sys.coinit_flags is not defined) - process hangs! So i've choosen COINIT_SPEED_OVER_MEMORY and everything became fine! The easiest way to set it is to do following before importing comtypes:

import sys
sys.coinit_flags = 0x8 # COINIT_SPEED_OVER_MEMORY == 0x8