问:
Unable to locate the element using css selector[JAVA]
Website: http://www.javatpoint.com/

Steps : First click on JAVA=>Scroll down and click on Java String => Substring

I'm trying to locate the webelement using cssSelector, but not able to locate the element whereas I'm able to locate the same using xpath.

```<code>driver.findElement(By.xpath("//div/a[text()='Substring']"));
</code>```

css Selectors I've tried :

```<code>driver.findElement(By.cssSelector("div>a[text='Substring']"));
driver.findElement(By.cssSelector("div>a:contains('Substring')"));
</code>```

答:
You can't select inner text using cssSelector, it is not possible to do that.
If you need to do that use xPath instead.

Body:
Website: http://www.javatpoint.com/

Steps : First click on JAVA=>Scroll down and click on Java String => Substring

I'm trying to locate the webelement using cssSelector, but not able to locate the element whereas I'm able to locate the same using xpath.

driver.findElement(By.xpath("//div/a[text()='Substring']"));

css Selectors I've tried :

driver.findElement(By.cssSelector("div>a[text='Substring']"));
driver.findElement(By.cssSelector("div>a:contains('Substring')"));


来源: stackexchange

问:
How to send values to another method
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

```<code>private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
</code>```

答:
The AsyncTask has generic types which in your case are Void, Void, Void. These 3 types are parameters for the methods

```<code>doInBackground(params...)
onProgressUpdate(params...)
</code>```

and

```<code>onPostExecute(Result)
</code>```

So if your first type would be String (AsyncTask<String, Void, Void>), your doInBackground method would look like

```<code>doInBackground(String... params) {
  String firstparam = params[0];
}
</code>```

Please consider to check if params is not null and it's size greater than 0

It's all documented here

ContentLicense: CC BY-SA 3.0

Title: How to send values to another method

Body:
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}

Body:
The AsyncTask has generic types which in your case are Void, Void, Void. These 3 types are parameters for the methods

doInBackground(params...)
onProgressUpdate(params...)

and

onPostExecute(Result)

So if your first type would be String (AsyncTask<String, Void, Void>), your doInBackground method would look like

doInBackground(String... params) {
  String firstparam = params[0];
}

Please consider to check if params is not null and it's size greater than 0

It's all documented here


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
Here's a loop-free approach using data.table's joins:

```<code>DT[, id := 1:.N]
dt <- melt(DT, id.vars = "id")
dt[, id2 := id-1]
dt <- dt[!is.na(value)]
idx <- dt[dt, on = .(id2 = id, value), nomatch=0][, unique(id)]
DT[, `:=`(D = as.integer(id %in% idx), id = NULL)]
</code>```

It looks somewhat complicated but id does perform pretty well with just over a second for a 1-million-row data set with three columns.

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
Here's a loop-free approach using data.table's joins:

DT[, id := 1:.N]
dt <- melt(DT, id.vars = "id")
dt[, id2 := id-1]
dt <- dt[!is.na(value)]
idx <- dt[dt, on = .(id2 = id, value), nomatch=0][, unique(id)]
DT[, `:=`(D = as.integer(id %in% idx), id = NULL)]

It looks somewhat complicated but id does perform pretty well with just over a second for a 1-million-row data set with three columns.


问:
Copy contents of one List into another List (not reference)
I have two List :

```<code>List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();
</code>```

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

答:
You can use concept of Java deep clone:

The basic idea is this:

You have a Java object, and you want to make a complete clone (copy) of it.
By marking your classes as being Serializable, you can write them out as an object stream, then read them back in as a different object.
When you read the object back in as a different object, you very quickly have a deep clone of your original object.

A Java deep clone method

Getting right to the answer, the following method will let you make a deep clone of a Java object:

```<code>/**
 * This method makes a "deep clone" of any Java object it is given.
 */
 public static Object deepClone(Object object) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(object);
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   }
   catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
</code>```

find more details in below link:

A Java deep clone (deep copy) example

Body:
I have two List :

List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

Body:
You can use concept of Java deep clone:

The basic idea is this:

You have a Java object, and you want to make a complete clone (copy) of it.
By marking your classes as being Serializable, you can write them out as an object stream, then read them back in as a different object.
When you read the object back in as a different object, you very quickly have a deep clone of your original object.

A Java deep clone method

Getting right to the answer, the following method will let you make a deep clone of a Java object:

/**
 * This method makes a "deep clone" of any Java object it is given.
 */
 public static Object deepClone(Object object) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(object);
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   }
   catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }

find more details in below link:

A Java deep clone (deep copy) example


问:
How to check for only checked checkboxes in an array in javascript
I am using code.org library. I am trying to use only checked checkboxes to select two teams for a baseball game. Currently I can only select 1 team but I need to select two teams effectively by not just going to the next team in the array. I have never see such problem in JavaScript.

```<code>onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var index = 0;
    while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
      index++;
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});
</code>```

答:
Put the selected ones in a new array.

Also, remember to check that you have succeeded in finding two before you let your program continue.

Example:

```<code>onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var selected = [];
    for (index = 0; selected.length < 2 && index < chkBoxs.length; index++) {
        if (getChecked(chkBoxs[index])) { selected.push(index); }
    }
    setScreen("game");
    if (selected.length == 2) {
        console.log("The Teams are: " + chkBoxs[selected[0]] + " and " + chkBoxs[selected[1]]);
    }
});
</code>```

Body:
I am using code.org library. I am trying to use only checked checkboxes to select two teams for a baseball game. Currently I can only select 1 team but I need to select two teams effectively by not just going to the next team in the array. I have never see such problem in JavaScript.

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var index = 0;
    while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
      index++;
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});

Body:
Put the selected ones in a new array.

Also, remember to check that you have succeeded in finding two before you let your program continue.

Example:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var selected = [];
    for (index = 0; selected.length < 2 && index < chkBoxs.length; index++) {
        if (getChecked(chkBoxs[index])) { selected.push(index); }
    }
    setScreen("game");
    if (selected.length == 2) {
        console.log("The Teams are: " + chkBoxs[selected[0]] + " and " + chkBoxs[selected[1]]);
    }
});


问:
How correctly generate html select option with php?
yesterday, I was designing a platform to enter products and their quantities using drop-down lists, but I had to generate them using a button, so I had to use javascript. It worked, but at the moment of sending the data by post only takes the last Select generated, then the code and the result.

```<code>    <form id="pedido" name="pedido" action="funciones/pedido.php" method="post" >

<table name="pedidos" class="table table-bordered table-hover" id="myTable">
                                 <thead>
                                    <tr>
                                        <th>Producto</th>
                                        <th>Cantidad</th>
                                    </tr>
                                </thead>

</table>
<br>

</form>
<center>
<button class="btn btn-sm btn-primary"  onclick="myCreateFunction()">Agregar Producto</button>
<button class="btn btn-sm btn-danger" onclick="myDeleteFunction()">Eliminar Producto</button>
<button class="btn btn-sm btn-success"  form="pedido" type="submit">Guardar</button></center>
<br>
</code>```

and the Javascript

```<code><script>
function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell = row.insertCell(0);

    <? $sql="select * from productodist where  rut_dist='".$_GET['id']."';";
$resultado=mysql_query($sql);
$x=0;?>
    var element = document.createElement("select");
 <? while($datos=mysql_fetch_array($resultado)){
     $x++?>
    var option<? echo $x; ?> = document.createElement("option");
    option<? echo $x; ?> .innerHTML = "<? echo  $datos['Descripcion'] ?>";
    option<? echo $x; ?>.value = "<? echo  $datos['CodArticulo'] ?>";
    element.add(option<? echo $x; ?>, null);
    element.name = "producto<? echo $x; ?>";

    <?
 }
    ?>
    cell.appendChild(element);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("select");
    //element2.type = "select"

    <?  for ($y=1;$y<=100;$y++){
        ?>    var option<? echo $y; ?> = document.createElement("option");
    option<? echo $y; ?>.innerHTML = "<? echo $y; ?>";
    option<? echo $y; ?>.value = "<? echo $y; ?>";
    element2.add(option<? echo $y; ?>, null);
    element2.name = "cantidad<? echo $x; ?>";
    <?  }?>
    cell2.appendChild(element2);
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(1);
}
</script>
</code>```

And then when I send it, the post array anwer me this.

```<code>Array ( [producto30] => 20008 [cantidad30] => 1 )
</code>```

What I'm doing wrong? Thanks you in advance!

答:
Here is how you generate HTML select option with PHP.

Put this at the top of your php script.

```<code><?php
$sql="select * from productodist where  rut_dist='".$_GET['id']."';";
$resultado=mysql_query($sql);
$datos=mysql_fetch_array($resultado);

$selectProducts = '';
$selectProducts .= '<select name="producto">'; // maybe add multiple attribute if you need multiple values sent
foreach($datos as $dato) {
    $selectProducts .= '<option value="'.$dato['CodArticulo'].'">'.$dato['Descripcion'].'</option>';
}
$selectProducts .= '</select>';
?>
</code>```

Then anywhere in your HTML you can display the select:

```<code><?php echo $selectProducts; ?>
</code>```

Remove that PHP mixup in your Javascript. It is really not the way to do this...

Note: Using <? instead of <?php is deprecated and can lead to errors that make your app fail to run on newer PHP versions.

Body:
yesterday, I was designing a platform to enter products and their quantities using drop-down lists, but I had to generate them using a button, so I had to use javascript. It worked, but at the moment of sending the data by post only takes the last Select generated, then the code and the result.

    <form id="pedido" name="pedido" action="funciones/pedido.php" method="post" >

                                        Producto
                                        Cantidad

</form>

<button class="btn btn-sm btn-primary"  onclick="myCreateFunction()">Agregar Producto</button>
<button class="btn btn-sm btn-danger" onclick="myDeleteFunction()">Eliminar Producto</button>
<button class="btn btn-sm btn-success"  form="pedido" type="submit">Guardar</button>

and the Javascript

And then when I send it, the post array anwer me this.

Array ( [producto30] => 20008 [cantidad30] => 1 )

What I'm doing wrong? Thanks you in advance!

Body:
Here is how you generate HTML select option with PHP.

Put this at the top of your php script.

<?php
$sql="select * from productodist where  rut_dist='".$_GET['id']."';";
$resultado=mysql_query($sql);
$datos=mysql_fetch_array($resultado);

$selectProducts = '';
$selectProducts .= '<select name="producto">'; // maybe add multiple attribute if you need multiple values sent
foreach($datos as $dato) {
    $selectProducts .= '<option value="'.$dato['CodArticulo'].'">'.$dato['Descripcion'].'</option>';
}
$selectProducts .= '</select>';
?>

Then anywhere in your HTML you can display the select:

<?php echo $selectProducts; ?>

Remove that PHP mixup in your Javascript. It is really not the way to do this...

Note: Using <? instead of <?php is deprecated and can lead to errors that make your app fail to run on newer PHP versions.


问:
Fill div with image without stretching
I have an image with high resolution (width: 5540px, height: 2680px), and I need
this image to cover an entire div (this div goes full width and 80% of height). This image is displayed on screens with resolutions of 768px till 1600px.

When I use background-size: cover, the image goes full width but the bottom part is cut off.

When I use background-size: contain, the image is resized to fit the height but the width isn't entirely filled.

When I user background-size: 100%, the image fill the entire div, but gets stretch out.

Is there any way to do that or do I need to resize the image (for example, resize image to 1600px (width) because this image is only displayed on screens with width from 768px to 1600px)?

答:
You can use Image Liquid js for it.
https://github.com/karacas/imgLiquid

Hope it will help you...

Title: Fill div with image without stretching


问:
php search table by id
Im trying to display all the information from a single row in my database table by the id.

When I click search it shows the entire table and the search really doesnt do anything..

Any help would be appreciated. Thank you :)

im using php/mysql

```<code><?php

session_start();
include('connect.php');
if(isset($_POST['search']))
{
$q = $_POST['srch_query'];

?>

<form method="post" action="">
<input type="text" name="srch_query" value="<?php echo $q ?>" required>
<input type="submit" name="search" value="Search">
</form>

<?php

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info");
$search->execute();
if($search->rowcount()==0){ echo "No product found!"; }
else
{
    echo "Search Result:</br>";?>
    <table border="1" cellspacing="0" cellpadding="4">
        <thead>
            <tr>
                <th>Species</th>
                <th>Description</th>
                <th>Age</th>
                <th>City</th>
                <th>State</th>
                <th>Location</th>
            </tr>
        </thead>

        <tbody>

    <?php foreach($search as $s)
        { ?>

            <tr class="record">
                <td><?php echo $s['species']; ?></td>
                <td><?php echo $s['tree_desc']; ?></td>
                <td><?php echo $s['age']; ?></td>
                <td><?php echo $s['city']; ?></td>
                <td><?php echo $s['state']; ?></td>
                <td><?php echo $s['location']; ?></td>
            </tr>

    <?php   }
}
} ?>

</tbody>
</table>
</code>```

答:
Your $search variable is a PDOStatement object. You need to fetch result.

Do it this way :

```<code><?php
    $results = $search->fetchAll();
    foreach($results as $s)
    { ?>

        <tr class="record">
            <td><?php echo $s['species']; ?></td>
            <td><?php echo $s['tree_desc']; ?></td>
            <td><?php echo $s['age']; ?></td>
            <td><?php echo $s['city']; ?></td>
            <td><?php echo $s['state']; ?></td>
            <td><?php echo $s['location']; ?></td>
        </tr>

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

And check the doc for more informations on the PDOStatement if needed.
http://php.net/manual/fr/class.pdostatement.php

EDIT : my bad, I was focusing on the wrong problem.

You must add your $q to your query if it exists :

```<code>if ($q) {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,   location FROM tree_info WHERE id = :id");
    $search->bindParam('id', $q, PDO::PARAM_INT);
} else {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,     location FROM tree_info");
}
</code>```

Title: php search table by id

Body:
Im trying to display all the information from a single row in my database table by the id.

When I click search it shows the entire table and the search really doesnt do anything..

Any help would be appreciated. Thank you :)

im using php/mysql

<?php

session_start();
include('connect.php');
if(isset($_POST['search']))
{
$q = $_POST['srch_query'];

?>

<form method="post" action="">
<input type="text" name="srch_query" value="<?php echo $q ?>" required>
<input type="submit" name="search" value="Search">
</form>

<?php

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info");
$search->execute();
if($search->rowcount()==0){ echo "No product found!"; }
else
{
    echo "Search Result:
";?>

                Species
                Description
                Age
                City
                State
                Location

    <?php foreach($search as $s)
        { ?>

                <?php echo $s['species']; ?>
                <?php echo $s['tree_desc']; ?>
                <?php echo $s['age']; ?>
                <?php echo $s['city']; ?>
                <?php echo $s['state']; ?>
                <?php echo $s['location']; ?>

    <?php   }
}
} ?>

Body:
Your $search variable is a PDOStatement object. You need to fetch result.

Do it this way :

<?php
    $results = $search->fetchAll();
    foreach($results as $s)
    { ?>

        <tr class="record">
            <td><?php echo $s['species']; ?></td>
            <td><?php echo $s['tree_desc']; ?></td>
            <td><?php echo $s['age']; ?></td>
            <td><?php echo $s['city']; ?></td>
            <td><?php echo $s['state']; ?></td>
            <td><?php echo $s['location']; ?></td>
        </tr>

<?php   }  ?>

And check the doc for more informations on the PDOStatement if needed.
http://php.net/manual/fr/class.pdostatement.php

EDIT : my bad, I was focusing on the wrong problem.

You must add your $q to your query if it exists :

if ($q) {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,   location FROM tree_info WHERE id = :id");
    $search->bindParam('id', $q, PDO::PARAM_INT);
} else {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,     location FROM tree_info");
}


问:
<authentication mode="Forms"> doesnt work?
I have a login-page where users can log in. When they logging in with correctly details they are sent to an main admin-page. If they cant log in they are staying on the login-page. What I want to do is, if a random user, type in the URL for an admin-page when they are not logged in they are redirecting to the login-page.

I have understood that I have to do it in the masterpage or webconfig!?! I have a main admin-page and some other admin-pages.

Any tips?

I tried to insert this into my webconfig:

```<code><authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>
</code>```

here is my code for the "login"-button (on the login-page);

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }
</code>```

The code on the "login"-page works for that page, but I actually want to check if user is logged in in the master-page. Is there something I can do in the masterpage to activate the forms authentication?

答:
Your code is missing a lot of pieces for FormsAuthentication.

First of all, the code is prone to SQL Injection attack. You want to consider using Parameterized Query.

Sign-In method

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    // After validation successful
    bool rememberMe = false; // Make it false for now
    FormsAuthentication.RedirectFromLoginPage(brukernavn.Text, rememberMe);
}
</code>```

Global.asax.cs

You need this in order to retrieve the username from cookie, and save it in IPrincipal Object.

```<code>public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}
</code>```

web.config

```<code><authentication mode="Forms">
   <forms loginUrl="~/InnUtlogging.aspx" />
</authentication>
</code>```

Usage

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string username = User.Identity.Name;
    }
}
</code>```

Body:
I have a login-page where users can log in. When they logging in with correctly details they are sent to an main admin-page. If they cant log in they are staying on the login-page. What I want to do is, if a random user, type in the URL for an admin-page when they are not logged in they are redirecting to the login-page.

I have understood that I have to do it in the masterpage or webconfig!?! I have a main admin-page and some other admin-pages.

Any tips?

I tried to insert this into my webconfig:

<authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>

here is my code for the "login"-button (on the login-page);

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }

The code on the "login"-page works for that page, but I actually want to check if user is logged in in the master-page. Is there something I can do in the masterpage to activate the forms authentication?

Body:
Your code is missing a lot of pieces for FormsAuthentication.

First of all, the code is prone to SQL Injection attack. You want to consider using Parameterized Query.

Sign-In method

protected void Button1_Click(object sender, EventArgs e)
{
    // After validation successful
    bool rememberMe = false; // Make it false for now
    FormsAuthentication.RedirectFromLoginPage(brukernavn.Text, rememberMe);
}

Global.asax.cs

You need this in order to retrieve the username from cookie, and save it in IPrincipal Object.

public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}

web.config

<authentication mode="Forms">
   <forms loginUrl="~/InnUtlogging.aspx" />
</authentication>

Usage

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string username = User.Identity.Name;
    }
}


问:
Nvarchar value overflowing an int column where there is no int column?
How is my nvarchar value overflowing an int column when I'm not defining any int values?

I'm getting the following error when I run my stored procedure:

```<code>The conversion of the nvarchar value '17191925814' overflowed an int column.
</code>```

The statement I was trying to execute:

```<code>EXECUTE [dbo].[updateUser] @status = 'active', ..... ,@srcID = '17191925814'
</code>```

The problem is that I never define that value as an int. It is always handled as a string, as far as I can tell. In my stored procedure the @srcID parameter is defined as an nvarchar(255):

```<code>CREATE PROCEDURE [dbo].[updateUser] ... , @srcID nvarchar(255), ...
</code>```

And within that stored procedure, I try to UPDATE a value in a column that is also defined as nvarchar(255):

```<code>IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL
    UPDATE [dbo].[Users] SET [Source System ID] = @srcID WHERE ...
ELSE IF @srcID = '0'
    UPDATE [dbo].[Users] SET [Source System ID] = '' WHERE ...
</code>```

The target table:

```<code>CREATE TABLE [dbo].[Users] ( ..., [Source System ID] [nvarchar](255) NULL, ...)
</code>```

Where, or why, is SQL Server trying to convert '17191925814' to an int, and how can I prevent it?

Edit: I've included the full code of the stored procedure where the parameter @srcID appears.

答:
The problem, as pointed out by Damian in the comments, was that I had a trigger active on the database, that was copying that data into an integer column.

So if you have this same issue: check triggers on your database!

Body:
How is my nvarchar value overflowing an int column when I'm not defining any int values?

I'm getting the following error when I run my stored procedure:

The conversion of the nvarchar value '17191925814' overflowed an int column.

The statement I was trying to execute:

EXECUTE [dbo].[updateUser] @status = 'active', ..... ,@srcID = '17191925814'

The problem is that I never define that value as an int. It is always handled as a string, as far as I can tell. In my stored procedure the @srcID parameter is defined as an nvarchar(255):

CREATE PROCEDURE [dbo].[updateUser] ... , @srcID nvarchar(255), ...

And within that stored procedure, I try to UPDATE a value in a column that is also defined as nvarchar(255):

IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL
    UPDATE [dbo].[Users] SET [Source System ID] = @srcID WHERE ...
ELSE IF @srcID = '0'
    UPDATE [dbo].[Users] SET [Source System ID] = '' WHERE ...

The target table:

CREATE TABLE [dbo].[Users] ( ..., [Source System ID] [nvarchar](255) NULL, ...)

Where, or why, is SQL Server trying to convert '17191925814' to an int, and how can I prevent it?

Edit: I've included the full code of the stored procedure where the parameter @srcID appears.


问:
Error code JS with my function Game Over
I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.

var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');

for( var i = 0; i <= 8; i++){
  $contener.innerHTML += "

";
}

if(localStorage.getItem('score')){
  $bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
  localStorage.setItem('score', 0);
  $bestscore.textContent = 'Score : 0';
}

function decompte(){
  if(compte <= 1) {
 pluriel = "";
  } else {
 pluriel = "s";
  }
  $compt.innerHTML = compte + " seconde" + pluriel;
  if(!compte || compte < 0) {
 reset();

 if(pointCounter > localStorage.getItem('score')){
   localStorage.setItem('score', pointCounter);
   $bestscore.textContent = 'Score : ' + pointCounter;
 }
  }
  //decrease 1 point
  compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);

//RANDOM POSITION
function randomPosition() {
  var $cases = document.querySelectorAll('.case');
  // cannot click 2 times
  for (var i =0; i< $cases.length; i++){
 $cases[i].removeEventListener('click', losePoints);
 $cases[i].removeEventListener('click', earnPoints);
 $cases[i].innerHTML = '';
  }

  var x = Math.floor(Math.random() * 9);
  var min = 1;
  var max = 7;
  var nbrRandom = min + Math.floor(Math.random() * max);

  if (nbrRandom === 2) {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', losePoints);
  } else if(nbrRandom ===6) {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', gameOver);
  }
  else
  {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', earnPoints);
  }
}

function losePoints(event){
  /* JouerSon(); */
  pointCounter -=10;
  if(pointCounter <0){
 pointCounter =0
  }
  $score.textContent = pointCounter;
  event.currentTarget.removeEventListener('click', losePoints);
}

function earnPoints(event){
  /*    JouerSon(); */

  pointCounter ++;
  $score.textContent = pointCounter;
  event.currentTarget.removeEventListener('click', earnPoints);
}

/*function JouerSon() {
 var sound = document.getElementById("beep");
 sound.play();
} */

// RESET BUTTON
function reset(){
  $button.classList.remove("reset");
  $button.addEventListener('click', resetGame);
  clearInterval(timer);
  clearInterval(taupe);
}

function resetGame(){
  pointCounter = 0;
  compte = temps;
  $score.textContent = pointCounter;
  timer = setInterval(decompte,1000);
  taupe = setInterval(randomPosition,1000);
  $button.removeEventListener('click', resetGame);
  $button.classList.add('reset');
}
function gameOver(event){
  event.currentTarget.removeEventListener('click', gameOver);
  alert("GAME OVER");
  reset();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
 <head>
  <link rel="stylesheet" type="text/css" href="styles/style.css">
  <meta charset="utf-8"/>
 </head>
 <body>
  <span id="compt"></span>
  <span id="score">Score : </span> <span id="bestscore"></span>
  <div class="contener"></div>
  <button class="resetBouton reset"> reset </button>
  <button class="resetBouton jouer"> Jouer </button>
  <audio id="beep" src="test1.wav">
  <script type='text/javascript' src="script/main.js"></script>
 </body>
</html></code>```

答:
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.

It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Body:
I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.

var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');

for( var i = 0; i <= 8; i++){
  $contener.innerHTML += "

";
}

if(localStorage.getItem('score')){
  $bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
  localStorage.setItem('score', 0);
  $bestscore.textContent = 'Score : 0';
}

function decompte(){
  if(compte <= 1) {
 pluriel = "";
  } else {
 pluriel = "s";
  }
  $compt.innerHTML = compte + " seconde" + pluriel;
  if(!compte || compte < 0) {
 reset();

 if(pointCounter > localStorage.getItem('score')){
   localStorage.setItem('score', pointCounter);
   $bestscore.textContent = 'Score : ' + pointCounter;
 }
  }
  //decrease 1 point
  compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);

//RANDOM POSITION
function randomPosition() {
  var $cases = document.querySelectorAll('.case');
  // cannot click 2 times
  for (var i =0; i< $cases.length; i++){
 $cases[i].removeEventListener('click', losePoints);
 $cases[i].removeEventListener('click', earnPoints);
 $cases[i].innerHTML = '';
  }

  var x = Math.floor(Math.random() * 9);
  var min = 1;
  var max = 7;
  var nbrRandom = min + Math.floor(Math.random() * max);

  if (nbrRandom === 2) {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', losePoints);
  } else if(nbrRandom ===6) {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', gameOver);
  }
  else
  {
 $cases[x].innerHTML = '

';
 $cases[x].addEventListener('click', earnPoints);
  }
}

function losePoints(event){
  /* JouerSon(); */
  pointCounter -=10;
  if(pointCounter <0){
 pointCounter =0
  }
  $score.textContent = pointCounter;
  event.currentTarget.removeEventListener('click', losePoints);
}

function earnPoints(event){
  /*    JouerSon(); */

  pointCounter ++;
  $score.textContent = pointCounter;
  event.currentTarget.removeEventListener('click', earnPoints);
}

/*function JouerSon() {
 var sound = document.getElementById("beep");
 sound.play();
} */

// RESET BUTTON
function reset(){
  $button.classList.remove("reset");
  $button.addEventListener('click', resetGame);
  clearInterval(timer);
  clearInterval(taupe);
}

function resetGame(){
  pointCounter = 0;
  compte = temps;
  $score.textContent = pointCounter;
  timer = setInterval(decompte,1000);
  taupe = setInterval(randomPosition,1000);
  $button.removeEventListener('click', resetGame);
  $button.classList.add('reset');
}
function gameOver(event){
  event.currentTarget.removeEventListener('click', gameOver);
  alert("GAME OVER");
  reset();

}

<!DOCTYPE HTML>

  <link rel="stylesheet" type="text/css" href="styles/style.css">
  <meta charset="utf-8"/>

  Score :

  <button class="resetBouton reset"> reset </button>
  <button class="resetBouton jouer"> Jouer </button>
  <audio id="beep" src="test1.wav">


问:
Hide iPhone HTML5 video play button
I want to hide the big play button that appears by default on the <video> element

Is it possible?

答:
For webapps.
Works iOS 10.3 iPhone7 & Safari 10.1 on Mac as well. Thx to previous contributors.
I had also the issue that the  element does not contain any "control" attribute at all.  </p>

```<code>'<style type="text/css">'+
    '*::-webkit-media-controls-panel {'+
     '   display: none!important;'+
      '  -webkit-appearance: none;'+
   ' }'+
    /* Old shadow dom for play button */
    '*::--webkit-media-controls-play-button {'+
        'display: none!important;'+
        '-webkit-appearance: none;'+
    '}'+
    /* New shadow dom for play button */
    /* This one works */
    '*::-webkit-media-controls-start-playback-button {'+
        'display: none!important;'+
       ' -webkit-appearance: none;'+
        '}'+
    +'</style>'
</code>```

Title: Hide iPhone HTML5 video play button

Body:
For webapps.
Works iOS 10.3 iPhone7 & Safari 10.1 on Mac as well. Thx to previous contributors.
I had also the issue that the  element does not contain any "control" attribute at all.

'<style type="text/css">'+
    '*::-webkit-media-controls-panel {'+
     '   display: none!important;'+
      '  -webkit-appearance: none;'+
   ' }'+
    /* Old shadow dom for play button */
    '*::--webkit-media-controls-play-button {'+
        'display: none!important;'+
        '-webkit-appearance: none;'+
    '}'+
    /* New shadow dom for play button */
    /* This one works */
    '*::-webkit-media-controls-start-playback-button {'+
        'display: none!important;'+
       ' -webkit-appearance: none;'+
        '}'+
    +'</style>'


问:
Php change color one cell text from stored proc
I use sql server stored proc where one column send me information about color, but i need to apply it one an other column but more exactly on one cell and not the complete row. For now, what i can do it's on the row only and i need to do it exclusively on the red one. Here's my code for now :

```<code>    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
    //print_r( $row );  // debug code
    $couleur='black';
    $font= 'normal';
    $font2= '#transparent';
    if( strstr($row['HTML_CODE'], "BOLD()")){
        $font= 'bold';
    }
    if( strstr($row['HTML_CODE'], "BG()")){
        $font2= '#D8D8D8';
    }
    if( strstr($row['HTML_CODE'], "RED()")){
        $couleur='red';
    }
?>
                            <tbody>
                                <tr>
                                    <?php echo "<tr style=\"font-weight:$font; color:$couleur; background-color:$font2;\">"; ?>
                                    <td><?php echo ($row['TextLine']);?></td>
                                    <td style="text-align: right"><?php echo is_null($row['TotalQty']) ? ' ' : number_format($row['TotalQty'],0,'',' ');?></td>
                                    <td style="text-align: right"><?php echo is_null($row['TotalAmountDrawer']) ? ' ' : number_format($row['TotalAmountDrawer'],2, ".", " ") . " $";?></td>
                                    <td style="text-align: right"><?php echo is_null($row['TotalAmountPickup']) ? ' ' : number_format($row['TotalAmountPickup'],2, ".", " ") . " $";?></td>
                                    <td style="text-align: right"><?php echo is_null($row['TotalAmountOverShort']) ? ' ' : number_format($row['TotalAmountOverShort'],2, ".", " ") . " $";?></td>
                                </tr>
                            </tbody>
<?php
}
 ?>
</code>```

I need to apply it on the column name  : TotalAmountOverShort only!

Thank you for your help, it's really appreciate!

答:
Change the CSS color rule from TR to TD.
If the background color also applies to only one cell, do the same with background-color:

```<code> <tr>
 <?php echo "<tr style=\"font-weight:$font; background-color:$font2;\">"; ?>
    <td><?php echo ($row['TextLine']);?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalQty']) ? ' ' : number_format($row['TotalQty'],0,'',' ');?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalAmountDrawer']) ? ' ' : number_format($row['TotalAmountDrawer'],2, ".", " ") . " $";?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalAmountPickup']) ? ' ' : number_format($row['TotalAmountPickup'],2, ".", " ") . " $";?></td>
    <td style="text-align: right; color: <?php echo $couleur; ?>"><?php echo is_null($row['TotalAmountOverShort']) ? ' ' : number_format($row['TotalAmountOverShort'],2, ".", " ") . " $";?></td>
</tr>
</code>```

Body:
I use sql server stored proc where one column send me information about color, but i need to apply it one an other column but more exactly on one cell and not the complete row. For now, what i can do it's on the row only and i need to do it exclusively on the red one. Here's my code for now :

    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
    //print_r( $row );  // debug code
    $couleur='black';
    $font= 'normal';
    $font2= '#transparent';
    if( strstr($row['HTML_CODE'], "BOLD()")){
        $font= 'bold';
    }
    if( strstr($row['HTML_CODE'], "BG()")){
        $font2= '#D8D8D8';
    }
    if( strstr($row['HTML_CODE'], "RED()")){
        $couleur='red';
    }
?>

                                    <?php echo "
"; ?>
                                    <?php echo ($row['TextLine']);?>
                                    <?php echo is_null($row['TotalQty']) ? ' ' : number_format($row['TotalQty'],0,'',' ');?>
                                    <?php echo is_null($row['TotalAmountDrawer']) ? ' ' : number_format($row['TotalAmountDrawer'],2, ".", " ") . " $";?>
                                    <?php echo is_null($row['TotalAmountPickup']) ? ' ' : number_format($row['TotalAmountPickup'],2, ".", " ") . " $";?>
                                    <?php echo is_null($row['TotalAmountOverShort']) ? ' ' : number_format($row['TotalAmountOverShort'],2, ".", " ") . " $";?>

<?php
}
 ?>

I need to apply it on the column name  : TotalAmountOverShort only!

Thank you for your help, it's really appreciate!

Body:
Change the CSS color rule from TR to TD.
If the background color also applies to only one cell, do the same with background-color:

 <tr>
 <?php echo "<tr style=\"font-weight:$font; background-color:$font2;\">"; ?>
    <td><?php echo ($row['TextLine']);?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalQty']) ? ' ' : number_format($row['TotalQty'],0,'',' ');?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalAmountDrawer']) ? ' ' : number_format($row['TotalAmountDrawer'],2, ".", " ") . " $";?></td>
    <td style="text-align: right"><?php echo is_null($row['TotalAmountPickup']) ? ' ' : number_format($row['TotalAmountPickup'],2, ".", " ") . " $";?></td>
    <td style="text-align: right; color: <?php echo $couleur; ?>"><?php echo is_null($row['TotalAmountOverShort']) ? ' ' : number_format($row['TotalAmountOverShort'],2, ".", " ") . " $";?></td>
</tr>


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Answer #2 :)

The actual language construct that first really fascinated me was recursion.  The problem

Write a function named SumDigits which
  summed the digits of a number. Example:
  SumDigits(1234) -> 10

At first I wrote a very long iterative solution.  But after awhile I came up with this answer.

```<code>string SumDigits(int value) {
  if ( value > 10 ) {
    return SumDigits(value/10) + (value%10);
  }
  return value;
}
</code>```

The succinctness of the answer amazed me and I instantly found a new love in recursion and terse programming.

It only took a couple of weeks though to learn the evils of recursion :)

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

Body:
Answer #2 :)

The actual language construct that first really fascinated me was recursion.  The problem

Write a function named SumDigits which
  summed the digits of a number. Example:
  SumDigits(1234) -> 10

At first I wrote a very long iterative solution.  But after awhile I came up with this answer.

string SumDigits(int value) {
  if ( value > 10 ) {
    return SumDigits(value/10) + (value%10);
  }
  return value;
}

The succinctness of the answer amazed me and I instantly found a new love in recursion and terse programming.

It only took a couple of weeks though to learn the evils of recursion :)

OwnerDisplayName: JaredPar


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答:
Maybe the software do this "strange" operation in order to support little/big endian architecture (byte order differ).

Conclusion:

On two different machine (little/big endian) if you insert binary information in your file, with a same input, file can be different.

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.


答:
Try this

```<code>new GetDirecoes().execute(latRepr,LngRepr);
</code>```

and after that

```<code>private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... params) {
      String latRepr = params[0];
      String LngRepr= params[1];

}
</code>```

Title: How to send values to another method

Body:
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}

Body:
Try this

new GetDirecoes().execute(latRepr,LngRepr);

and after that

private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... params) {
      String latRepr = params[0];
      String LngRepr= params[1];

}


问:
MultiThreading Windows Application
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

```<code>    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));
</code>```

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#

答:
Since they live in the same form, they will all belong to the same GUI thread. This means that you can use any of them (or their parent form) as the invoke target, and do all operations within one invoke:

```<code>this.Invoke(new MethodInvoker(() =>
{
    strFrom = txtFrom.Text;
    strTo = txtTo.Text;
    strMessageBody = txtMessageBody.Text;
    strStartDate = txtStartDate.Text;
    strEndDate = txtEndDate.Text;
    intStatus = ddlStatus.SelectedIndex;
}));
</code>```

I am not sure this solves your problem, but it at least simplifies your code.

Title: MultiThreading Windows Application

Body:
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#

Body:
Since they live in the same form, they will all belong to the same GUI thread. This means that you can use any of them (or their parent form) as the invoke target, and do all operations within one invoke:

this.Invoke(new MethodInvoker(() =>
{
    strFrom = txtFrom.Text;
    strTo = txtTo.Text;
    strMessageBody = txtMessageBody.Text;
    strStartDate = txtStartDate.Text;
    strEndDate = txtEndDate.Text;
    intStatus = ddlStatus.SelectedIndex;
}));

I am not sure this solves your problem, but it at least simplifies your code.


问:
How can I share existing memory with shm_open?
In Linux, I want to share some memory content of my process with other processes.
one of the way to do this is using shm_open and mmap. like below.

```<code>/* Create a new memory object */
fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 );
if( fd == -1 ) {
    fprintf( stderr, "Open failed:%s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Set the memory object's size */
if( ftruncate( fd, sizeof( *addr ) ) == -1 ) {
    fprintf( stderr, "ftruncate: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Map the memory object */
addr = mmap( 0, sizeof( *addr ),
        PROT_READ | PROT_WRITE,
        MAP_SHARED, fd, 0 );
if( addr == MAP_FAILED ) {
    fprintf( stderr, "mmap failed: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}
</code>```

However, in this way, I can't share the "already allocated memory".
my question is :
can I share the previously allocated memory contents without re-allocating them?.

thank you in advance.

答:
Your code does share the memory but both your processes will get different address regions. You want to have the same region, so addr value will be the same. In this case you can build objects in this memory, use internal pointers and your objects will be valid and visible in both processes.

There are two methods how you can do that.

1) do fork() to create another process

2) ask mmap to allocate memory at the special address with MAP_FIXED.

For number two your code will looks:

```<code>/* Create a new memory object */
fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 );
if( fd == -1 ) {
    fprintf( stderr, "Open failed:%s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Set the memory object's size */
if( ftruncate( fd, sizeof( *addr ) ) == -1 ) {
    fprintf( stderr, "ftruncate: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

// You base address for memory region that you want to share.
// Choose this carefully, you both processes MUST have it available!
void * baseAddr = 0x7fff00000000;

/* Map the memory object */
addr = mmap( baseAddr, sizeof( *addr ),
        PROT_READ | PROT_WRITE,
        MAP_SHARED | MAP_FIXED, fd, 0 );

if( addr == MAP_FAILED | MAP_FIXED ) {
    fprintf( stderr, "mmap failed: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}
</code>```

Body:
In Linux, I want to share some memory content of my process with other processes.
one of the way to do this is using shm_open and mmap. like below.

/* Create a new memory object */
fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 );
if( fd == -1 ) {
    fprintf( stderr, "Open failed:%s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Set the memory object's size */
if( ftruncate( fd, sizeof( *addr ) ) == -1 ) {
    fprintf( stderr, "ftruncate: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Map the memory object */
addr = mmap( 0, sizeof( *addr ),
        PROT_READ | PROT_WRITE,
        MAP_SHARED, fd, 0 );
if( addr == MAP_FAILED ) {
    fprintf( stderr, "mmap failed: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

However, in this way, I can't share the "already allocated memory".
my question is :
can I share the previously allocated memory contents without re-allocating them?.

thank you in advance.

Body:
Your code does share the memory but both your processes will get different address regions. You want to have the same region, so addr value will be the same. In this case you can build objects in this memory, use internal pointers and your objects will be valid and visible in both processes.

There are two methods how you can do that.

1) do fork() to create another process

2) ask mmap to allocate memory at the special address with MAP_FIXED.

For number two your code will looks:

/* Create a new memory object */
fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 );
if( fd == -1 ) {
    fprintf( stderr, "Open failed:%s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

/* Set the memory object's size */
if( ftruncate( fd, sizeof( *addr ) ) == -1 ) {
    fprintf( stderr, "ftruncate: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}

// You base address for memory region that you want to share.
// Choose this carefully, you both processes MUST have it available!
void * baseAddr = 0x7fff00000000;

/* Map the memory object */
addr = mmap( baseAddr, sizeof( *addr ),
        PROT_READ | PROT_WRITE,
        MAP_SHARED | MAP_FIXED, fd, 0 );

if( addr == MAP_FAILED | MAP_FIXED ) {
    fprintf( stderr, "mmap failed: %s\n",
        strerror( errno ) );
    return EXIT_FAILURE;
}


问:
Creating zip archive in Java
I have one file created by 7zip program. I used deflate method to compress it. Now I want to create the same archive (with the same MD5sum) in java. When I create zip file, I used the algorithm that I found on the Internet for example http://www.kodejava.org/examples/119.html but when I created zip file with this method the compressed size is higher than size of the uncompressed file so what is going on? This isn't a very useful compression. So how I can create zip file that is exactly same as zip file that I created with 7zip program ? If it helps I have all information about zip file that I created in 7zip program.

答:
Please find in the below code having the functionalities to zip and unzip. Hope it may help someone.

```<code>package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @author dinesh.lomte
 *
 */
public class ZipUtil {

    /**
     *
     * @param source
     * @param destination
     */
    public static void unZip(String source, String destination) {

        String method = "unZip(String source, String destination)";
        ZipInputStream zipInputStream = null;
        try {
            // Creating the ZipInputStream instance from the source file
            zipInputStream = new ZipInputStream(new FileInputStream(source));
            // Getting the zipped file list entry
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            // Iterating through the file list entry
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File file = new File(new StringBuilder(destination)
                    .append(File.separator)
                    .append(AppUtil.getFileNameWithoutExtension(
                            AppUtil.getNameFromPath(source)))
                    .append(File.separator).append(fileName).toString());
                // Creating non existing folders to avoid any FileNotFoundException
                // for compressed folder
                new File(file.getParent()).mkdirs();
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                fileOutputStream.close();
                zipEntry = zipInputStream.getNextEntry();
            }
        } catch (IOException iOException) {
            System.out.println("Failed to unzip the ''{0}'' file located in ''{1}'' folder. Due to, {2}");

        } finally {
            // Validating if zipInputStream instance in not null
            if (zipInputStream != null) {
                try {
                    zipInputStream.closeEntry();
                    zipInputStream.close();
                } catch (IOException iOException) {
                }
            }
        }
    }

    /**
     * Traverse a directory from the source folder location and get all files,
     * and add the file into files list.
     *
     * @param node
     */
    public static void generateFileList(
            String source, File node, List<String> files) {
        // Validating if the node is a file
        if (node.isFile()) {
            files.add(generateZipEntry(
                    source, node.getPath().toString()));
        }
        // Validating if the node is a directory
        if (node.isDirectory()) {
            String[] subNote = node.list();
            for (String filename : subNote) {
                generateFileList(source, new File(node, filename), files);
            }
        }
    }

    /**
     * Format the file path to zip
     * @param source
     * @param file
     * @return
     */
    private static String generateZipEntry(String source, String file) {
        return file.substring(source.length(), file.length());
    }

    /**
     *
     * @param source
     * @param destination
     */
    public static void zip(String source, String destination) {

        String method = "zip(String source, String destination)";
        ZipOutputStream zipOutputStream = null;
        try {
            // Creating the zipOutputStream instance
            zipOutputStream = new ZipOutputStream(
                    new FileOutputStream(destination));
            List<String> files = new ArrayList<>();
            generateFileList(source, new File(source), files);
            // Iterating the list of file(s) to zip/compress
            for (String file : files) {
                // Adding the file(s) to the zip
                ZipEntry zipEntry = new ZipEntry(file);
                zipOutputStream.putNextEntry(zipEntry);
                FileInputStream fileInputStream = new FileInputStream(
                        new StringBuilder(source).append(File.separator)
                        .append(file).toString());
                int length;
                byte[] buffer = new byte[1024];
                while ((length = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, length);
                }
                // Closing the fileInputStream instance
                fileInputStream.close();
                // De-allocating the memory by assigning the null value
                fileInputStream = null;
            }
        } catch (IOException iOException) {
            System.out.println("Failed to zip the file(s) located in ''{0}'' folder. Due to, {1}");
        } finally {
            // Validating if zipOutputStream instance in not null
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.closeEntry();
                    zipOutputStream.close();
                } catch (IOException iOException) {
                }
            }
        }
    }
}
</code>```

Title: Creating zip archive in Java

Body:
Please find in the below code having the functionalities to zip and unzip. Hope it may help someone.

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @author dinesh.lomte
 *
 */
public class ZipUtil {

    /**
     *
     * @param source
     * @param destination
     */
    public static void unZip(String source, String destination) {

        String method = "unZip(String source, String destination)";
        ZipInputStream zipInputStream = null;
        try {
            // Creating the ZipInputStream instance from the source file
            zipInputStream = new ZipInputStream(new FileInputStream(source));
            // Getting the zipped file list entry
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            // Iterating through the file list entry
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File file = new File(new StringBuilder(destination)
                    .append(File.separator)
                    .append(AppUtil.getFileNameWithoutExtension(
                            AppUtil.getNameFromPath(source)))
                    .append(File.separator).append(fileName).toString());
                // Creating non existing folders to avoid any FileNotFoundException
                // for compressed folder
                new File(file.getParent()).mkdirs();
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                fileOutputStream.close();
                zipEntry = zipInputStream.getNextEntry();
            }
        } catch (IOException iOException) {
            System.out.println("Failed to unzip the ''{0}'' file located in ''{1}'' folder. Due to, {2}");

        } finally {
            // Validating if zipInputStream instance in not null
            if (zipInputStream != null) {
                try {
                    zipInputStream.closeEntry();
                    zipInputStream.close();
                } catch (IOException iOException) {
                }
            }
        }
    }

    /**
     * Traverse a directory from the source folder location and get all files,
     * and add the file into files list.
     *
     * @param node
     */
    public static void generateFileList(
            String source, File node, List<String> files) {
        // Validating if the node is a file
        if (node.isFile()) {
            files.add(generateZipEntry(
                    source, node.getPath().toString()));
        }
        // Validating if the node is a directory
        if (node.isDirectory()) {
            String[] subNote = node.list();
            for (String filename : subNote) {
                generateFileList(source, new File(node, filename), files);
            }
        }
    }

    /**
     * Format the file path to zip
     * @param source
     * @param file
     * @return
     */
    private static String generateZipEntry(String source, String file) {
        return file.substring(source.length(), file.length());
    }

    /**
     *
     * @param source
     * @param destination
     */
    public static void zip(String source, String destination) {

        String method = "zip(String source, String destination)";
        ZipOutputStream zipOutputStream = null;
        try {
            // Creating the zipOutputStream instance
            zipOutputStream = new ZipOutputStream(
                    new FileOutputStream(destination));
            List<String> files = new ArrayList<>();
            generateFileList(source, new File(source), files);
            // Iterating the list of file(s) to zip/compress
            for (String file : files) {
                // Adding the file(s) to the zip
                ZipEntry zipEntry = new ZipEntry(file);
                zipOutputStream.putNextEntry(zipEntry);
                FileInputStream fileInputStream = new FileInputStream(
                        new StringBuilder(source).append(File.separator)
                        .append(file).toString());
                int length;
                byte[] buffer = new byte[1024];
                while ((length = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, length);
                }
                // Closing the fileInputStream instance
                fileInputStream.close();
                // De-allocating the memory by assigning the null value
                fileInputStream = null;
            }
        } catch (IOException iOException) {
            System.out.println("Failed to zip the file(s) located in ''{0}'' folder. Due to, {1}");
        } finally {
            // Validating if zipOutputStream instance in not null
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.closeEntry();
                    zipOutputStream.close();
                } catch (IOException iOException) {
                }
            }
        }
    }
}


问:
getting only one data from laravel collection seems difficult
I don't get this, I have a collection of items.
The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection.
The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ??
This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.

```<code>//returns all items with 'item_color_id" = 1

$item = Item::where(//some constraints);

$filtered = $item->filter(function ($i) {
                return $i->item_color_id == 1;
            });

if (count($filtered)) {

    //need to access a single data inside the collection
    // like for example 'item_brand_id'
    //I can do it like this:

    $filtered = $filtered->values();

    $item_brand_id = $filtered[0]['item_brand_id'];

    //but what sense does it have?? how can we access 'item_brand_id'
    //from $filtered without resetting the indexes?

}
</code>```

it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it.
For example I coould use max() or min() on $filtered like this:

```<code>$max_brand_id = $filtered->max('item_brand_id');
</code>```

It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage.
I tried only('item_brand_id); but that returns empty while the data is there.

答:
You still have eloquent collection so you can do just call first() function

```<code>$item_brand_id = $filtered->first()->item_brand_id;
</code>```

Body:
I don't get this, I have a collection of items.
The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection.
The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ??
This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.

//returns all items with 'item_color_id" = 1

$item = Item::where(//some constraints);

$filtered = $item->filter(function ($i) {
                return $i->item_color_id == 1;
            });

if (count($filtered)) {

    //need to access a single data inside the collection
    // like for example 'item_brand_id'
    //I can do it like this:

    $filtered = $filtered->values();

    $item_brand_id = $filtered[0]['item_brand_id'];

    //but what sense does it have?? how can we access 'item_brand_id'
    //from $filtered without resetting the indexes?

}

it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it.
For example I coould use max() or min() on $filtered like this:

$max_brand_id = $filtered->max('item_brand_id');

It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage.
I tried only('item_brand_id); but that returns empty while the data is there.

Body:
You still have eloquent collection so you can do just call first() function

$item_brand_id = $filtered->first()->item_brand_id;


问:
heroku: no default language could be detected for this app
First time using Heroku. Trying to push. I have run the command:

heroku create --buildpack heroku/python

and it displayed

```<code>$ heroku create --buildpack heroku/python
Creating app... done, glacial-reef-7599
Setting buildpack to heroku/python... done
https://glacial-reef-7599.herokuapp.com/ | https://git.heroku.com/glacial-reef-7599.git
</code>```

Stack trace:

```<code>$ git push heroku master
Counting objects: 129, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (124/124), done.
Writing objects: 100% (129/129), 69.06 KiB | 0 bytes/s, done.
Total 129 (delta 22), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to pure-badlands-9125.
remote:
To https://git.heroku.com/pure-badlands-9125.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pure-badlands-9125.git'
</code>```

I've gotta be missing something.

I have added a requirements.txt to my root directory. It looks like this:

```<code>.git
.idea
projectapp
projectname
rango
db.sqlite3
manage.py
populate_rango.py
requirements.txt
</code>```

答:
Heroku’s Python support extends to the latest stable release from the Python 2.x and Python 3.x series.
Today, this support extends to these specific runtimes:

python-2.7.13

python-3.6.1

try to change your python version in runtime.txt

Body:
First time using Heroku. Trying to push. I have run the command:

heroku create --buildpack heroku/python

and it displayed

$ heroku create --buildpack heroku/python
Creating app... done, glacial-reef-7599
Setting buildpack to heroku/python... done
https://glacial-reef-7599.herokuapp.com/ | https://git.heroku.com/glacial-reef-7599.git

Stack trace:

$ git push heroku master
Counting objects: 129, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (124/124), done.
Writing objects: 100% (129/129), 69.06 KiB | 0 bytes/s, done.
Total 129 (delta 22), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to pure-badlands-9125.
remote:
To https://git.heroku.com/pure-badlands-9125.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pure-badlands-9125.git'

I've gotta be missing something.

I have added a requirements.txt to my root directory. It looks like this:

.git
.idea
projectapp
projectname
rango
db.sqlite3
manage.py
populate_rango.py
requirements.txt


问:
Disable multiple numbers after zero in input type="number"
This is my HTML:

```<code><input type="number" min="0" oninput="validity.valid||(value='');" step="0.1"/>
</code>```

However, I can still type something like:

0000 or 000111 or 00223, etc.

in my input field. How can I limit it only to one 0?

Is there a way to do this in HTML only?

Thanks.

答:
I'd go with something like this:

```<code>while (s.charAt(0) == '0') {
    if (s.length == 1) { break };
    if (s.charAt(1) == '.') { break };
    s = s.substr(1, s.length-1)
}
</code>```

It accepts numbers like 0.1 and handles 00.1 or 001.

Body:
This is my HTML:

<input type="number" min="0" oninput="validity.valid||(value='');" step="0.1"/>

However, I can still type something like:

0000 or 000111 or 00223, etc.

in my input field. How can I limit it only to one 0?

Is there a way to do this in HTML only?

Thanks.

Body:
I'd go with something like this:

while (s.charAt(0) == '0') {
    if (s.length == 1) { break };
    if (s.charAt(1) == '.') { break };
    s = s.substr(1, s.length-1)
}

It accepts numbers like 0.1 and handles 00.1 or 001.


问:
SQL - retrieve maximum date from other related table
I have  table T1 with data:

```<code>ID GROUP
1  L1
2  L1
3  L2
4  L3
</code>```

I have table T2 with data:

```<code>ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017
</code>```

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

```<code>ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017
</code>```

I tried with this sql but it throws error:

```<code>        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)
</code>```

答:
Hmmm.  I think of this in terms of a correlated subquery:</p>

```<code>select t1.*,
       (select max(t2.date)
        from t2
        where t2.id = t1.id and t1.group <> 'L1'
       ) as date
from t1;
</code>```

Body:
I have  table T1 with data:

ID GROUP
1  L1
2  L1
3  L2
4  L3

I have table T2 with data:

ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017

I tried with this sql but it throws error:

        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)

Body:
Hmmm.  I think of this in terms of a correlated subquery:

select t1.*,
       (select max(t2.date)
        from t2
        where t2.id = t1.id and t1.group <> 'L1'
       ) as date
from t1;


问:
Sporadic Python error in while loop TypeError: 'int' object is not iterable
Here's the portion of my script having errors:

```<code>while:
    sensorIn = 8
    sensorOut = 5
    sensorAC = 7
    blue = 0
    white = 1
    [tempIn, humIn] = grovepi.dht(sensorIn, 1)
    print("tempIn = %.02f C humIn =%.02f%%"%(tempIn, humIn))
    [tempOut, humOut] = grovepi.dht(sensorOut, 1)
    print("tempOut = %.02f C humOut =%.02f%%"%(tempOut, humOut))
    [tempAC, humAC] = grovepi.dht(sensorAC, 1)
    print("tempAC = %.02f C humAC =%.02f%%"%(tempAC, humAC))
</code>```

It randomly errors out with:

```<code>TypeError: 'int' object not iterable on the line: [tempAC, humAC] = grovepi.dht(sensorAC, 1)
</code>```

This is used with a Raspberry Pi and GrovePi board to take in readings from a temperature and humidity sensor. It will loop through, taking readings and then doing some things with those readings then sleep for 15 minutes before starting again.

Maybe the while loop is the issue...I used to run this without the while loop and would set it up in crontab to run every 15 minutes that way. Occasionally a reading would come in in error but would pass through the script as 0, the script would not stop and error out, it would continue through and just report the value as zero.

I've looked at a lot of different posts about this error but I've only come across ones where the error always comes up and doesn't allow the script to run through completion at all, in my case, it only happens occasionally.

答:
It looks like this is a known issue with the grovepi.dht function, caused occasionally possibly by issues with communication with the device. http://forum.dexterindustries.com/t/incorrect-readings-and-typeerror/1582/2

The solution is just to add exception handling for the type error, since it will just be an intermittent issue (see the linked post for an example of how to do this).

Body:
Here's the portion of my script having errors:

while:
    sensorIn = 8
    sensorOut = 5
    sensorAC = 7
    blue = 0
    white = 1
    [tempIn, humIn] = grovepi.dht(sensorIn, 1)
    print("tempIn = %.02f C humIn =%.02f%%"%(tempIn, humIn))
    [tempOut, humOut] = grovepi.dht(sensorOut, 1)
    print("tempOut = %.02f C humOut =%.02f%%"%(tempOut, humOut))
    [tempAC, humAC] = grovepi.dht(sensorAC, 1)
    print("tempAC = %.02f C humAC =%.02f%%"%(tempAC, humAC))

It randomly errors out with:

TypeError: 'int' object not iterable on the line: [tempAC, humAC] = grovepi.dht(sensorAC, 1)

This is used with a Raspberry Pi and GrovePi board to take in readings from a temperature and humidity sensor. It will loop through, taking readings and then doing some things with those readings then sleep for 15 minutes before starting again.

Maybe the while loop is the issue...I used to run this without the while loop and would set it up in crontab to run every 15 minutes that way. Occasionally a reading would come in in error but would pass through the script as 0, the script would not stop and error out, it would continue through and just report the value as zero.

I've looked at a lot of different posts about this error but I've only come across ones where the error always comes up and doesn't allow the script to run through completion at all, in my case, it only happens occasionally.


问:
Internationalization - Loading many locales and the supplemental data
The example only shows loading of 1 locale which is bg.
How are we able to load all the locale so that we can change the locale dynamically. Thanks in advance!

http://plnkr.co/edit/Ucx0SlcmBfN9TRjrS5Ad?p=preview Plunker

答:
[Short answer]

You can't change the locale of the Angular application dynamically, without recreating the module/component.

[Long version]

The locale of the Angular component is determined by the LOCALE_ID, which is injected through the Angular DI system. Considering the fact the Angular uses constructor based dependency injection, the component needs to be recreated in order to receive new LOCALE_ID value.

That being said, the only feasible solution to have components/modules with different locales is to wrap them with high order component that will provide different LOCALE_ID:

```<code>@Component({
  selector: 'bg',
  providers: [{
    provide: LOCALE_ID,
    useValue: 'bg-BG'
  }, {
    provide: IntlService,
    useFactory: (localeId: string) => new CldrIntlService(localeId),
    deps: [LOCALE_ID]
  }],
  template: `
    <ng-content></ng-content>
  `
})
export class BGComponent {
}
</code>```

Here is runnable demo:
http://plnkr.co/edit/gmAWVLD1Yzn353QA1eDj?p=preview

Please note, that the plunker demonstrates how to place components with different locale on one page. As I mentioned, fully dynamic change of the locale is not possible (excluding the all possible hacks, of course). If there is a good solution out there using LOCALE_ID, I'd be more than happy to see it.

Body:
[Short answer]

You can't change the locale of the Angular application dynamically, without recreating the module/component.

[Long version]

The locale of the Angular component is determined by the LOCALE_ID, which is injected through the Angular DI system. Considering the fact the Angular uses constructor based dependency injection, the component needs to be recreated in order to receive new LOCALE_ID value.

That being said, the only feasible solution to have components/modules with different locales is to wrap them with high order component that will provide different LOCALE_ID:

@Component({
  selector: 'bg',
  providers: [{
    provide: LOCALE_ID,
    useValue: 'bg-BG'
  }, {
    provide: IntlService,
    useFactory: (localeId: string) => new CldrIntlService(localeId),
    deps: [LOCALE_ID]
  }],
  template: `
    <ng-content></ng-content>
  `
})
export class BGComponent {
}

Here is runnable demo:
http://plnkr.co/edit/gmAWVLD1Yzn353QA1eDj?p=preview

Please note, that the plunker demonstrates how to place components with different locale on one page. As I mentioned, fully dynamic change of the locale is not possible (excluding the all possible hacks, of course). If there is a good solution out there using LOCALE_ID, I'd be more than happy to see it.


问:
How to remove blanks/NA's from dataframe and shift the values up
I have a huge dataframe which has values and blanks/NA's in it. I want to remove the blanks from the dataframe and move the next values up in the column. Consider below sample dataframe.

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
df

       0           1           2         3
0   1.857476      NaN      -0.462941   -0.600606
1   0.000267   -0.540645    NaN        0.492480
2   NaN           NaN      -0.803889   0.527973
3   0.566922    0.036393   -1.584926   2.278294
4   -0.243182   -0.221294   1.403478   1.574097
</code>```

I want my output to be as below

```<code>       0             1             2           3
0   1.857476    -0.540645     -0.462941   -0.600606
1   0.000267     0.036393     -0.803889    0.492480
2   0.566922    -0.221294     -1.584926    0.527973
3   -0.243182                  1.403478    2.278294
4                                          1.574097
</code>```

I want the NaN to be removed and the next value to move up. df.shift was not helpful. I tried with multiple loops and if statements and achieved the desired result but is there any better way to get it done.

答:
A numpy approach

The idea is to sort the columns by np.isnan so that np.nans are put last.  I use kind='mergesort' to preserve the order within non np.nan.  Finally, I slice the array and reassign it.  I follow this up with a fillna

```<code>v = df.values
i = np.arange(v.shape[1])
a = np.isnan(v).argsort(0, kind='mergesort')
v[:] = v[a, i]
print(df.fillna(''))

          0         1         2         3
0   1.85748 -0.540645 -0.462941 -0.600606
1  0.000267  0.036393 -0.803889  0.492480
2  0.566922 -0.221294  -1.58493  0.527973
3 -0.243182             1.40348  2.278294
4                                1.574097
</code>```

If you didn't want to alter the dataframe in place

```<code>v = df.values
i = np.arange(v.shape[1])
a = np.isnan(v).argsort(0, kind='mergesort')
pd.DataFrame(v[a, i], df.index, df.columns).fillna('')
</code>```

The point of this is to leverage numpys quickness

naive time test

Body:
I have a huge dataframe which has values and blanks/NA's in it. I want to remove the blanks from the dataframe and move the next values up in the column. Consider below sample dataframe.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
df

       0           1           2         3
0   1.857476      NaN      -0.462941   -0.600606
1   0.000267   -0.540645    NaN        0.492480
2   NaN           NaN      -0.803889   0.527973
3   0.566922    0.036393   -1.584926   2.278294
4   -0.243182   -0.221294   1.403478   1.574097

I want my output to be as below

       0             1             2           3
0   1.857476    -0.540645     -0.462941   -0.600606
1   0.000267     0.036393     -0.803889    0.492480
2   0.566922    -0.221294     -1.584926    0.527973
3   -0.243182                  1.403478    2.278294
4                                          1.574097

I want the NaN to be removed and the next value to move up. df.shift was not helpful. I tried with multiple loops and if statements and achieved the desired result but is there any better way to get it done.

Body:
A numpy approach

The idea is to sort the columns by np.isnan so that np.nans are put last.  I use kind='mergesort' to preserve the order within non np.nan.  Finally, I slice the array and reassign it.  I follow this up with a fillna

v = df.values
i = np.arange(v.shape[1])
a = np.isnan(v).argsort(0, kind='mergesort')
v[:] = v[a, i]
print(df.fillna(''))

          0         1         2         3
0   1.85748 -0.540645 -0.462941 -0.600606
1  0.000267  0.036393 -0.803889  0.492480
2  0.566922 -0.221294  -1.58493  0.527973
3 -0.243182             1.40348  2.278294
4                                1.574097

If you didn't want to alter the dataframe in place

v = df.values
i = np.arange(v.shape[1])
a = np.isnan(v).argsort(0, kind='mergesort')
pd.DataFrame(v[a, i], df.index, df.columns).fillna('')

The point of this is to leverage numpys quickness

naive time test


答: some file formats require the byte order to be in a single way normally big endian as that's network order so on little endian x86s those files have their ints byte swapped when written and swapped back when read</p>

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.


问:
Convert string date long format to 12h date format
I have a function that works well if the format is in 24h but however in 12h it does not work well, I'm trying to apply this to correct it but the result of the 3 line is 'nil', some reason why this is happening?

```<code>  let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017-02-01 14:55:08")
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    let stringdate = dateFormatter.string(from: date)
    let newDate12h = dateFormatter.date(from: stringdate)
</code>```

this line return nil :

```<code>let date = dateFormatter.date(from: "2017-02-01 14:55:08")
</code>```

答:
I does work when add this line :</p>

```<code>dateFormatter.locale = Locale.init(identifier:"es_ES")
</code>```

Body:
I have a function that works well if the format is in 24h but however in 12h it does not work well, I'm trying to apply this to correct it but the result of the 3 line is 'nil', some reason why this is happening?

  let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017-02-01 14:55:08")
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    let stringdate = dateFormatter.string(from: date)
    let newDate12h = dateFormatter.date(from: stringdate)

this line return nil :

let date = dateFormatter.date(from: "2017-02-01 14:55:08")

Body:
I does work when add this line :

dateFormatter.locale = Locale.init(identifier:"es_ES")