问:
How do I use AES_Decrypt
I know this question has been asked a billion times as I've spent the last 2 weeks looking at all the previously asked questions and answers
but none of them actually have an understandable answer. So my question is this, I have a form that I'm passing the data input by users into a mysql
database and a portion of that data is encrypted with AES_Encrypt. When I check the database I can see the data has been encrypted so I'm good on the encryption part.
My issue lies in the decryption part. I've tried multiple variations from previous questions asked with no success, This is what I have so far,

```<code>//ENCRYPTING DATA
require 'path to key.php';

$sql = "INSERT INTO applications "(fname, lname, dob, ssn) VALUES  ('$fname', '$lname', '$dob', AES_ENCRYPT('$ssn', '".$aeskey."')";
</code>```

The code above works fine to encrypt the string.

This is where I'm confused, I'm wanting to select all the data associated with the ID for a record and decrypt the encrypted data for that record as well,
for example I have a search form that pulls up all the records in the database, you can then select to view a record and the results display in a form similar to the form used
to input the information.

So in my form to view records I have the following code.

```<code>//DECRYPT DATA

require 'path to key.php';

$conn = new mysqli($servername, $username, $password, $dbname);

$data = "SELECT * FROM $tbl_name where ID = $id";

$query = mysqli_query($conn, $data);

$data2 = mysqli_fetch_array($query);

<input type = "text" name="fname" value="<?php echo $data2['fname']?>"/>
<input type = "text" name="lname" value="<?php echo $data2['lname']?>"/>
<input type = "text" name="dob"   value="<?php echo $data2['dob']?>"/>
<input type = "text" name="ssn"   value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form
</code>```

So do I need to decrypt the encrypted data from the input box like

```<code> <input type = "text" name="ssn" value=<?php echo [AES_DECRYPT('ssn', '$aeskey')]?>"/> <---Doesn't work
</code>```

or do I need to do something like this:

```<code>$sql SELECT * FROM $tbl_name (AES_DECRYPT('ssn', '$aeskey')) WHERE ID=$id;
</code>```

Or am I totally wrong in how I think AES_DECRYPT should be used?

答:
In the INSERT you use AES_ENCRYPT (of MySQL); then you have in your SELECT apply AES_DECRYPT; ejem:

```<code>SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
FROM applications [wHERE ... and other more that you require]
</code>```

See that AES_DECRYPT have alias to return of result.

EDITED

Only change in $data the string with the SQL:

```<code>$data= "SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
        FROM applications [WHERE ... and other more that you require]"
</code>```

You line: <input type = "text" name="ssn"   value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form not change; unless instead of ssn (all in lowercase) in the alias you change some letter or all the letters to capital letters, you assign another alias name to the decrypted text; In order not to be ssn (in lower case).

Title: How do I use AES_Decrypt

Body:
I know this question has been asked a billion times as I've spent the last 2 weeks looking at all the previously asked questions and answers
but none of them actually have an understandable answer. So my question is this, I have a form that I'm passing the data input by users into a mysql
database and a portion of that data is encrypted with AES_Encrypt. When I check the database I can see the data has been encrypted so I'm good on the encryption part.
My issue lies in the decryption part. I've tried multiple variations from previous questions asked with no success, This is what I have so far,

//ENCRYPTING DATA
require 'path to key.php';

$sql = "INSERT INTO applications "(fname, lname, dob, ssn) VALUES  ('$fname', '$lname', '$dob', AES_ENCRYPT('$ssn', '".$aeskey."')";

The code above works fine to encrypt the string.

This is where I'm confused, I'm wanting to select all the data associated with the ID for a record and decrypt the encrypted data for that record as well,
for example I have a search form that pulls up all the records in the database, you can then select to view a record and the results display in a form similar to the form used
to input the information.

So in my form to view records I have the following code.

//DECRYPT DATA

require 'path to key.php';

$conn = new mysqli($servername, $username, $password, $dbname);

$data = "SELECT * FROM $tbl_name where ID = $id";

$query = mysqli_query($conn, $data);

$data2 = mysqli_fetch_array($query);

<input type = "text" name="fname" value="<?php echo $data2['fname']?>"/>
<input type = "text" name="lname" value="<?php echo $data2['lname']?>"/>
<input type = "text" name="dob"   value="<?php echo $data2['dob']?>"/>
<input type = "text" name="ssn"   value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form

So do I need to decrypt the encrypted data from the input box like

 <input type = "text" name="ssn" value=<?php echo [AES_DECRYPT('ssn', '$aeskey')]?>"/> <---Doesn't work

or do I need to do something like this:

$sql SELECT * FROM $tbl_name (AES_DECRYPT('ssn', '$aeskey')) WHERE ID=$id;

Or am I totally wrong in how I think AES_DECRYPT should be used?

Body:
In the INSERT you use AES_ENCRYPT (of MySQL); then you have in your SELECT apply AES_DECRYPT; ejem:

SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
FROM applications [wHERE ... and other more that you require]

See that AES_DECRYPT have alias to return of result.

EDITED

Only change in $data the string with the SQL:

$data= "SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
        FROM applications [WHERE ... and other more that you require]"

You line: <input type = "text" name="ssn"   value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form not change; unless instead of ssn (all in lowercase) in the alias you change some letter or all the letters to capital letters, you assign another alias name to the decrypted text; In order not to be ssn (in lower case).


来源: stackexchange

问:
(Yii2) the page that you are looking for used information.....?
my simple view file

```<code><?php
 use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php ActiveForm::begin()?>

 <?=Html::submitButton('something')?>

 <?php ActiveForm::end()?
</code>```

Clicked the button. After I reload the page and browser shows me
this

So how can I remove this?

答: This is basic browser behavior. Your form is doing a POST request and obviously when you try to refresh it will ask for this. Even if you write a basic html page without yii, you will still have this.</p>

ContentLicense: CC BY-SA 3.0

Body:
my simple view file

<?php
 use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php ActiveForm::begin()?>

 <?=Html::submitButton('something')?>

 <?php ActiveForm::end()?

Clicked the button. After I reload the page and browser shows me
this

So how can I remove this?


问:
iOS Nested UITableView Loading All Cells Unnecessarily
In 2 of my view controllers I have table views in which one or more of the cells contain a nested UITableView, which contains a further 20-30 cells.

The top level table loads cells as necessary, when the cells come into view, but the nested table seems to request all the cells at once even if only the top cell is visible. How can this be prevented?

答:
Are you using dynamic sized cells?

If so, you need to specify proper height of the cells either by UITableView.estimatedRowHeight or UITableViewDelegate.estimatedHeightForRowAtIndexPath:.

I usually cache the height of the cell on UITableViewDelegate.willDisplayCell:forRowAtIndexPath: and use the cached height at UITableViewDelegate.estimatedHeightForRowAtIndexPath:.

That solved the similar problem I had.

Otherwise, all the cells are loaded in the beginning even though they are not on screen.


问:
MySQL - Update Column Value with Function and Trigger Before Insert
i'm trying to update 2 column with trigger before insert, but i have unexpected result. i insert some data and the 2 last column will automatically inserted with values, here my first attempt

see? the last 2 column is null even i set some trigger and function to fill that columns automatically. Here my second attempt WITH EXACTLY SAME DATA

the last 2 column is filled with data, but i don't understand why the first attempt is fail?

here my trigger i use in the column total_harga

```<code>CREATE TRIGGER `set_total_harga` BEFORE INSERT ON `tbl_transaksi_detail`
 FOR EACH ROW BEGIN
set NEW.total_harga = hitungTotalHargaPerItem(NEW.qty, NEW.harga_satuan);
END
</code>```

trigger for column harga_satuan

```<code>CREATE TRIGGER `set_harga_satuan` BEFORE INSERT ON `tbl_transaksi_detail`
 FOR EACH ROW BEGIN
set NEW.harga_satuan = set_Harga_Unit(NEW.unit, NEW.id_barang, NEW.no_transaksi);
END
</code>```

function set_Harga_Unit

```<code>  BEGIN
  DECLARE
    q,
    id_toko INT;
  SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  ); IF unit = "PCS" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_pcs`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "PAK" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_pak`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "KARTON" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_karton`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q;
END IF; RETURN q;
END
</code>```

function hitungTotalHargaPerItem

```<code>BEGIN
DECLARE hasil int;
    set hasil = qty * harga_satuan;
    RETURN hasil;
END
</code>```

答:
it seem i have mistaken select query in function set_Harga_Unit, based on clues from @Shadow

```<code>SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`<<== I DON'T NEED THIS
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  ); IF unit = "PCS" THEN
</code>```

when first insert in tbl_transaksi_detail, the value no_transaksi is null because i use trigger before insert in empty table (tbl_transaksi_detail), so i remove tbl_transaksi_detail from query

```<code>SET
        id_toko =(
        SELECT DISTINCT
          `tbl_transaksi`.`id_toko`
        FROM
          `tbl_transaksi`
        WHERE
          `tbl_transaksi`.`no_transaksi` = no_trans
      ); IF unit = "PCS" THEN
</code>```

now it working, thanks everybody!

Body:
i'm trying to update 2 column with trigger before insert, but i have unexpected result. i insert some data and the 2 last column will automatically inserted with values, here my first attempt

see? the last 2 column is null even i set some trigger and function to fill that columns automatically. Here my second attempt WITH EXACTLY SAME DATA

the last 2 column is filled with data, but i don't understand why the first attempt is fail?

here my trigger i use in the column total_harga

CREATE TRIGGER `set_total_harga` BEFORE INSERT ON `tbl_transaksi_detail`
 FOR EACH ROW BEGIN
set NEW.total_harga = hitungTotalHargaPerItem(NEW.qty, NEW.harga_satuan);
END

trigger for column harga_satuan

CREATE TRIGGER `set_harga_satuan` BEFORE INSERT ON `tbl_transaksi_detail`
 FOR EACH ROW BEGIN
set NEW.harga_satuan = set_Harga_Unit(NEW.unit, NEW.id_barang, NEW.no_transaksi);
END

function set_Harga_Unit

  BEGIN
  DECLARE
    q,
    id_toko INT;
  SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  ); IF unit = "PCS" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_pcs`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "PAK" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_pak`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "KARTON" THEN
SET
  q =(
  SELECT
    `tbl_harga_jual`.`harga_karton`
  FROM
    `tbl_harga_jual`
  WHERE
    `tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q;
END IF; RETURN q;
END

function hitungTotalHargaPerItem

BEGIN
DECLARE hasil int;
    set hasil = qty * harga_satuan;
    RETURN hasil;
END

Body:
it seem i have mistaken select query in function set_Harga_Unit, based on clues from @Shadow

SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`<<== I DON'T NEED THIS
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  ); IF unit = "PCS" THEN

when first insert in tbl_transaksi_detail, the value no_transaksi is null because i use trigger before insert in empty table (tbl_transaksi_detail), so i remove tbl_transaksi_detail from query

SET
        id_toko =(
        SELECT DISTINCT
          `tbl_transaksi`.`id_toko`
        FROM
          `tbl_transaksi`
        WHERE
          `tbl_transaksi`.`no_transaksi` = no_trans
      ); IF unit = "PCS" THEN

now it working, thanks everybody!


问:
NoSuchMethodError using Databricks Spark-Avro 3.2.0
I have a spark master & worker running in Docker containers with spark 2.0.2 and hadoop 2.7. I'm trying to submit a job from pyspark from a different container (same network) by running

```<code>df = spark.read.json("/data/test.json")
df.write.format("com.databricks.spark.avro").save("/data/test.avro")
</code>```

But I'm getting this error:

```<code>java.lang.NoSuchMethodError: org.apache.avro.generic.GenericData.createDatumWriter(Lorg/apache/avro/Schema;)Lorg/apache/avro/io/DatumWriter;
</code>```

It makes no difference if I try interactively or with spark-submit. These are my loaded packages in spark:

```<code>com.databricks#spark-avro_2.11;3.2.0 from central in [default]
com.thoughtworks.paranamer#paranamer;2.7 from central in [default]
org.apache.avro#avro;1.8.1 from central in [default]
org.apache.commons#commons-compress;1.8.1 from central in [default]
org.codehaus.jackson#jackson-core-asl;1.9.13 from central in [default]
org.codehaus.jackson#jackson-mapper-asl;1.9.13 from central in [default]
org.slf4j#slf4j-api;1.7.7 from central in [default]
org.tukaani#xz;1.5 from central in [default]
org.xerial.snappy#snappy-java;1.1.1.3 from central in [default]
</code>```

spark-submit --version output:

```<code>Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.0.2
      /_/

Branch
Compiled by user jenkins on 2016-11-08T01:39:48Z
Revision
Url
Type --help for more information.
</code>```

scala version is 2.11.8

My pyspark command:

```<code>PYSPARK_PYTHON=ipython /usr/spark-2.0.2/bin/pyspark --master spark://master:7077 --packages com.databricks:spark-avro_2.11:3.2.0,org.apache.avro:avro:1.8.1
</code>```

My spark-submit command:

```<code>spark-submit script.py --master spark://master:7077 --packages com.databricks:spark-avro_2.11:3.2.0,org.apache.avro:avro:1.8.1
</code>```

I've read here that this can be caused by "an older version of avro being used" so I tried using 1.8.1, but I keep getting the same error. Reading avro works fine. Any help?

答:
I have encountered a similar problem before.
Try using --jars {path to spark-avro_2.11-3.2.0.jar} option in spark-submit

Body:
I have a spark master & worker running in Docker containers with spark 2.0.2 and hadoop 2.7. I'm trying to submit a job from pyspark from a different container (same network) by running

df = spark.read.json("/data/test.json")
df.write.format("com.databricks.spark.avro").save("/data/test.avro")

But I'm getting this error:

java.lang.NoSuchMethodError: org.apache.avro.generic.GenericData.createDatumWriter(Lorg/apache/avro/Schema;)Lorg/apache/avro/io/DatumWriter;

It makes no difference if I try interactively or with spark-submit. These are my loaded packages in spark:

com.databricks#spark-avro_2.11;3.2.0 from central in [default]
com.thoughtworks.paranamer#paranamer;2.7 from central in [default]
org.apache.avro#avro;1.8.1 from central in [default]
org.apache.commons#commons-compress;1.8.1 from central in [default]
org.codehaus.jackson#jackson-core-asl;1.9.13 from central in [default]
org.codehaus.jackson#jackson-mapper-asl;1.9.13 from central in [default]
org.slf4j#slf4j-api;1.7.7 from central in [default]
org.tukaani#xz;1.5 from central in [default]
org.xerial.snappy#snappy-java;1.1.1.3 from central in [default]

spark-submit --version output:

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.0.2
      /_/

Branch
Compiled by user jenkins on 2016-11-08T01:39:48Z
Revision
Url
Type --help for more information.

scala version is 2.11.8

My pyspark command:

PYSPARK_PYTHON=ipython /usr/spark-2.0.2/bin/pyspark --master spark://master:7077 --packages com.databricks:spark-avro_2.11:3.2.0,org.apache.avro:avro:1.8.1

My spark-submit command:

spark-submit script.py --master spark://master:7077 --packages com.databricks:spark-avro_2.11:3.2.0,org.apache.avro:avro:1.8.1

I've read here that this can be caused by "an older version of avro being used" so I tried using 1.8.1, but I keep getting the same error. Reading avro works fine. Any help?


问:
What Mercurial DVCS hosting would you recommend for a small open source project?
I'm looking around for free Mercurial hosting for a small-scale open-source project.

If you've ever used such a service, who is doing the hosting, and would you recommend them?

I know SF.net can be set up to host HG repos, but it looks like a lot of trouble (for the benefit of having a big, known, service that's unlikely to go down anytime soon).

There's also the list of free HG hosts right in Mercurial's official documentation, but I'd like to hear from those that actually got down and dirty with it :-)

答: This wasn't the case when this question was originally asked, but since January 2010 Microsoft's CodePlex can host Mercurial repositories as well.</p>

OwnerDisplayName: Cristi Diaconescu

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie


问:
Kubernetes not scheduling failed pod on other node
I have 4 nodes kubernetes cluster. My application running with 2 replica instances. I am using deployment resource with replica set. As per the documentation , replica set always ensure that specified no. Of application instances will be running.If I delete the one pod instance, then it will be restarted on the same or different node.But when I simulated the failure of a pod instance by stopping docker engine on one node. Kubectl shows status as error for the pod instance but do not restart the pod on another node. Is it the expected behaviour or am I missing something. </p>

答: Just wait for about 5 mins of bringing down the node or docker on it. Kubernetes marks the status of all the pods which were running on that node as 'Unknown' and will bring them up on the remaining active eligible nodes. Once the failed node comes back up, the pods on that node would be deleted if K8S already has them replaced on other node(s).</p>


问:
C++ usage: what does " *(new int); " do?
I saw a usage of the * operator in front of the new operator. What does it do?

```<code>int x= *(new int);
</code>```

答:
```<code>new int
</code>```

is allocating memory.

By using defering operator * you are getting the value present at that memory location which would be garbage.

```<code>#include <iostream>

void main()
{
    int x = *(new int);
    std::cout << x;
    system("pause");
}
</code>```

But this will cause the memory leak.

Body:
I saw a usage of the * operator in front of the new operator. What does it do?

int x= *(new int);

Body:
new int

is allocating memory.

By using defering operator * you are getting the value present at that memory location which would be garbage.

#include <iostream>

void main()
{
    int x = *(new int);
    std::cout << x;
    system("pause");
}

But this will cause the memory leak.


问:
How to subtract or add date from a variable?
I have a date in the variable x=20170402, getting this value from another file.

I want to modify this by adding/subtracting and save to new variable. How can i do this?

ex: if i subtract one day, y=20170401; two days, y=20170331

and it is GNU based.

答:
-d flag for this would serve the purpose. $Number is the number of days you wish to substract.

```<code>x=20170402
past_date=$(date -d "$x - $Number days" +%Y%m%d)
echo "$past_date"
</code>```

Body:
-d flag for this would serve the purpose. $Number is the number of days you wish to substract.

x=20170402
past_date=$(date -d "$x - $Number days" +%Y%m%d)
echo "$past_date"


问:
I want to get id of multiple checkboxes
I want id of selected items from checkbox and insert to database. I can insert other items to database but id of selected checkbox is not inserting.

```<code>    <div class="row" >
      <div class="col-xs-3">
      <form action="itemad.php" method="post">

      <div class="multiselect">
      <input type="text" name="datepicker" id="datepicker" placeholder="Date"     </p>
        <b>Select Menu:</b>
          <div class="checkbox" onclick="showCheckboxes()">
            <select>
                  <option>Select an option</option>
           </select>
         <div class="overSelect"></div>
        </div>

     <div id="checkboxes">

        <?php
            include 'connection.php';
           $query="select item from item";
            $result=mysql_query("$query");
             while($row=mysql_fetch_array($result)):;
              echo $row['item'];
               for($i=0; $i<=count('item'); $i++ )
        ?>
      <input type="checkbox" name="check_list[]" value="" ></input><br>
           <?php endwhile;?>
           </div>
         <input type="text" name="price" Placeholder="Pricee" minlength="1" ><br><br>
         <input type="submit" name="submit">
      </div>
     </div>
          <script type="text/javascript">
            var expanded = false;
            function showCheckboxes() {
              var checkboxes = document.getElementById("checkboxes");
              if (!expanded)
              {
                checkboxes.style.display = "block";
                expanded = true;
              }
              else
               {
                checkboxes.style.display = "none";
                expanded = false;
               }
            }
          </script>
  </form>
  </div>
  </div>
</code>```

itemad.php:

```<code>if(isset($_POST['submit']))
{
if(!empty($_POST['check_list']))
{
    // Counting number of checked checkboxes.
    $checked_count = count($_POST['check_list']);
    echo "You have selected following ".$checked_count." option(s): <br/>";
    // Loop to store and display values of individual checked checkbox.
    foreach($_POST['check_list'] as $id)
        {
            echo "<p>".$id ."</p>";
        } }
else
    { echo "<b>Please Select Atleast One Option.</b>"; }
   $price=$_POST['price'];
        $date=$_POST['datepicker'];
        $query= "insert into menu(item,price,date) values('$id','$price','$date')";
       $result=mysql_query($query);
       echo "suucesful";
    }
</code>```

i want to store id of each item in database. but in database i am not getting id for selected items.

答:
```<code><div class="row" >
    <div class="col-xs-3">
        <form action="itemad.php" method="post">

            <div class="multiselect">
                <input type="text" name="datepicker" id="datepicker" placeholder="Date" />
                <b>Select Menu:</b>
                <div class="checkbox" onclick="showCheckboxes()">
                    <select>
                        <option>Select an option</option>
                    </select>
                    <div class="overSelect"></div>
                </div>

                <div id="checkboxes">
                    <?php
                    include 'connection.php';
                    $query="select item_id, item from item";
                    $result=mysql_query("$query");
                    while($row=mysql_fetch_array($result)):;
                        echo $row['item'];
                    ?>
                        <input type="checkbox" name="check_list[]" value="<?php echo $row['item_id']; ?>" /><br>
                    <?php endwhile;?>
                </div>
                <input type="text" name="price" Placeholder="Price" minlength="1" ><br><br>
                <input type="submit" name="submit">
            </div>
            <script type="text/javascript">
            var expanded = false;
            function showCheckboxes() {
              if (!expanded)
              {
                $('#checkboxes input:checkbox').each(function () {
                   this.style.display = "block";
                });
                expanded = true;
              }
              else
               {
                $('#checkboxes input:checkbox').each(function () {
                   this.style.display = "none";
                });
                expanded = false;
               }
            }
            </script>
        </form>
    </div>
</div>
</code>```

itemad.php:

```<code>if(isset($_POST['submit']))
{
    if(!empty($_POST['check_list']))
    {
        // Counting number of checked checkboxes.
        $checked_count = count($_POST['check_list']);
        echo "You have selected following ".$checked_count." option(s): <br/>";
        // Loop to store and display values of individual checked checkbox.
        foreach($_POST['check_list'] as $id)
        {
            echo "<p>".$id ."</p>";
            $price=$_POST['price'];
            $date=$_POST['datepicker'];
            $query= "insert into menu(item,price,date) values('$id','$price','$date')";
            $result=mysql_query($query);
            echo "suucesful";
        }
    }
    else
    {
        echo "<b>Please Select Atleast One Option.</b>";
    }
}
</code>```

Title: I want to get id of multiple checkboxes

Body:
I want id of selected items from checkbox and insert to database. I can insert other items to database but id of selected checkbox is not inserting.

      <form action="itemad.php" method="post">

      <input type="text" name="datepicker" id="datepicker" placeholder="Date"

        Select Menu:

            <select>
                  <option>Select an option</option>
           </select>

        <?php
            include 'connection.php';
           $query="select item from item";
            $result=mysql_query("$query");
             while($row=mysql_fetch_array($result)):;
              echo $row['item'];
               for($i=0; $i<=count('item'); $i++ )
        ?>
      <input type="checkbox" name="check_list[]" value="" ></input>

           <?php endwhile;?>

         <input type="text" name="price" Placeholder="Pricee" minlength="1" >

         <input type="submit" name="submit">

  </form>

itemad.php:

if(isset($_POST['submit']))
{
if(!empty($_POST['check_list']))
{
    // Counting number of checked checkboxes.
    $checked_count = count($_POST['check_list']);
    echo "You have selected following ".$checked_count." option(s):
";
    // Loop to store and display values of individual checked checkbox.
    foreach($_POST['check_list'] as $id)
        {
            echo "
".$id ."
";
        } }
else
    { echo "Please Select Atleast One Option."; }
   $price=$_POST['price'];
        $date=$_POST['datepicker'];
        $query= "insert into menu(item,price,date) values('$id','$price','$date')";
       $result=mysql_query($query);
       echo "suucesful";
    }

i want to store id of each item in database. but in database i am not getting id for selected items.

Body:
<div class="row" >
    <div class="col-xs-3">
        <form action="itemad.php" method="post">

            <div class="multiselect">
                <input type="text" name="datepicker" id="datepicker" placeholder="Date" />
                <b>Select Menu:</b>
                <div class="checkbox" onclick="showCheckboxes()">
                    <select>
                        <option>Select an option</option>
                    </select>
                    <div class="overSelect"></div>
                </div>

                <div id="checkboxes">
                    <?php
                    include 'connection.php';
                    $query="select item_id, item from item";
                    $result=mysql_query("$query");
                    while($row=mysql_fetch_array($result)):;
                        echo $row['item'];
                    ?>
                        <input type="checkbox" name="check_list[]" value="<?php echo $row['item_id']; ?>" /><br>
                    <?php endwhile;?>
                </div>
                <input type="text" name="price" Placeholder="Price" minlength="1" ><br><br>
                <input type="submit" name="submit">
            </div>
            <script type="text/javascript">
            var expanded = false;
            function showCheckboxes() {
              if (!expanded)
              {
                $('#checkboxes input:checkbox').each(function () {
                   this.style.display = "block";
                });
                expanded = true;
              }
              else
               {
                $('#checkboxes input:checkbox').each(function () {
                   this.style.display = "none";
                });
                expanded = false;
               }
            }
            </script>
        </form>
    </div>
</div>

itemad.php:

if(isset($_POST['submit']))
{
    if(!empty($_POST['check_list']))
    {
        // Counting number of checked checkboxes.
        $checked_count = count($_POST['check_list']);
        echo "You have selected following ".$checked_count." option(s): <br/>";
        // Loop to store and display values of individual checked checkbox.
        foreach($_POST['check_list'] as $id)
        {
            echo "<p>".$id ."</p>";
            $price=$_POST['price'];
            $date=$_POST['datepicker'];
            $query= "insert into menu(item,price,date) values('$id','$price','$date')";
            $result=mysql_query($query);
            echo "suucesful";
        }
    }
    else
    {
        echo "<b>Please Select Atleast One Option.</b>";
    }
}


问:
Delphi - OLE variant passing problem (RsLinx OPC, Group Adding working with only from constants)
We got OPC job. I cannot installed RsLinx to my Win7 (and XP mode too) because of errors, so I send my test app to the real place, and somebody testing it.

Because I don't have DLL, I cannot make Delphi interface, so I need to do OLE Calls only.

I got an interesting problem with Group Add.

I demonstrate it:

```<code>procedure TForm1.Button8Click(Sender: TObject);
var
    r, g : variant;
    s : string;
    v : variant;
    ws : WideString;
begin
    Log('Connect');
    r := CreateOleObject('RSI.OPCAutomation');
    r.Connect('RSLinx OPC Server');

    Log('Add as constant');
    g := r.OPCGroups.Add('MONKEY_C');
    Log('Name ' + g.Name);

    Log('Add as string');
    s := 'MONKEY_S';
    g := r.OPCGroups.Add(s);
    Log('Name ' + g.Name);

    Log('Add as variant');
    s := 'MONKEY_V';
    v := s;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as ole variant');
    s := 'MONKEY_OV';
    v := VarAsType(s, varOleStr);
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as widestring');
    s := 'MONKEY_WS';
    ws := WideString(s);
    g := r.OPCGroups.Add(ws);
    Log('Name ' + g.Name);

    Log('Add as widestring var');
    s := 'MONKEY_WSV';
    ws := WideString(s);
    v := ws;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    r := 0;

end;
</code>```

The result was:

```<code>Connect
Add as constant
Name MONKEY_C
Add as string
Name _Group0
Add as variant
Name _Group1
Add as ole variant
Name _Group2
Add as widestring
Name _Group3
Add as widestring var
Name _Group4
</code>```

So the problem that I cannot add any Group than constant defined...

I need to know HOW Delphi compile this constant to I can convert my variant value to this format.

Can anybody help me in this theme?

Thanks:
   dd

Hi!

So the problem is mysterious.
I found another errors in the pure OLE calls.

```<code>function TDDRsOPCObject.IndexOfGroup(GroupName: string): integer;
var
    ogs, g : variant;
    i : integer;
    s : string;
begin
    CheckObject;
    Result := -1;
    ogs := FObj.OPCGroups;
    s := '';
    for i := 1 to ogs.Count  do begin
        g := ogs.Item(i); // This is working
        if AnsiCompareText(g.Name, GroupName) = 0 then begin
            Result := i;
            Exit;
        end;
    end;
end;

function TDDRsOPCObject.GetGroupByName(GroupName: string): variant;
var
    idx : integer;
    ogs, g : variant;
begin
    CheckObject;
    VarClear(Result);
    idx := IndexOfGroup(GroupName);
    ogs := FObj.OPCGroups;
    if idx <> -1
        then begin
            g := ogs.Item(idx); // HERE I GOT:  The parameter is incorrect
            Result := g;
        end;
end;
</code>```

So it is interesting: the IndexOfGroup with same call is working, the GetGroupByName is not... :-(

So I determined I do not continue my fighting with windmills (Don Q).
I got TLB from a dear user that have Delphi7 (in Win7 the Delphi6 cannot produce OLE interface), and I found Kassl.

May these interfaces can help me...

Thanks:
    dd

答:
As far as I know the constant and the strings are all converted to an OleString/BSTR (WideString). But since you are having these problems... probably not.

What does the documentation of OPCGroups.Add say? What is expected?

Do you have a type library? Maybe you can import them and use the interface directly.

Edit:

The documentation isn't very clear.

There are a few things you can try:

Check in CPU view what the Delphi compiler made of the code with the constant, maybe you see some hints there about what to do with your strings.

Try this code.

code:

```<code>const
  OPC_GROUP_NAME: WideString = 'MONKEY_C';
<...>
  g := r.OPCGroups.Add(OPC_GROUP_NAME);
  Log('Name ' + g.Name);
</code>```

When above code works, try this:

```<code>const
{$J+} //writable constants on
  OPC_GROUP_NAME: WideString = 'dummy';
{$J-}
<...>
  OPC_GROUP_NAME := 'MONKEY_BLA';
  g := r.OPCGroups.Add(OPC_GROUP_NAME);
  Log('Name ' + g.Name); //should be: 'Name MONKEY_BLA'
</code>```

Note: I don't like step 2, but if it works.. why not. To me it seems like there is a bug in the com-library you use.

Edit2:

I looked at the code generated by using the constant and using a normal string. With the constant I see the address of the first character being pushed on the stack, with the string I see the address of a pointer to a string being pushed on the stack.

With the code below I can simulate the same behaviour as with the constant:

```<code>var
  lWideArray: array[0..40] of WideChar;
  s: string;
  i: Integer;
<..>
s := 'MONKEY_FOO';
for i := 0 to Length(lWideArray) - 1 do
begin
  if i < Length(s) then
    lWideArray[i] := WideChar(s[i+1])
  else
    lWideArray[i] := #0;
end;

g := r.OPCGroups.Add(WideString(lWideArray));
Log('Name ' + g.Name);
</code>```

Body:
We got OPC job. I cannot installed RsLinx to my Win7 (and XP mode too) because of errors, so I send my test app to the real place, and somebody testing it.

Because I don't have DLL, I cannot make Delphi interface, so I need to do OLE Calls only.

I got an interesting problem with Group Add.

I demonstrate it:

procedure TForm1.Button8Click(Sender: TObject);
var
    r, g : variant;
    s : string;
    v : variant;
    ws : WideString;
begin
    Log('Connect');
    r := CreateOleObject('RSI.OPCAutomation');
    r.Connect('RSLinx OPC Server');

    Log('Add as constant');
    g := r.OPCGroups.Add('MONKEY_C');
    Log('Name ' + g.Name);

    Log('Add as string');
    s := 'MONKEY_S';
    g := r.OPCGroups.Add(s);
    Log('Name ' + g.Name);

    Log('Add as variant');
    s := 'MONKEY_V';
    v := s;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as ole variant');
    s := 'MONKEY_OV';
    v := VarAsType(s, varOleStr);
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as widestring');
    s := 'MONKEY_WS';
    ws := WideString(s);
    g := r.OPCGroups.Add(ws);
    Log('Name ' + g.Name);

    Log('Add as widestring var');
    s := 'MONKEY_WSV';
    ws := WideString(s);
    v := ws;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    r := 0;

end;

The result was:

Connect
Add as constant
Name MONKEY_C
Add as string
Name _Group0
Add as variant
Name _Group1
Add as ole variant
Name _Group2
Add as widestring
Name _Group3
Add as widestring var
Name _Group4

So the problem that I cannot add any Group than constant defined...

I need to know HOW Delphi compile this constant to I can convert my variant value to this format.

Can anybody help me in this theme?

Thanks:
   dd

Hi!

So the problem is mysterious.
I found another errors in the pure OLE calls.

function TDDRsOPCObject.IndexOfGroup(GroupName: string): integer;
var
    ogs, g : variant;
    i : integer;
    s : string;
begin
    CheckObject;
    Result := -1;
    ogs := FObj.OPCGroups;
    s := '';
    for i := 1 to ogs.Count  do begin
        g := ogs.Item(i); // This is working
        if AnsiCompareText(g.Name, GroupName) = 0 then begin
            Result := i;
            Exit;
        end;
    end;
end;

function TDDRsOPCObject.GetGroupByName(GroupName: string): variant;
var
    idx : integer;
    ogs, g : variant;
begin
    CheckObject;
    VarClear(Result);
    idx := IndexOfGroup(GroupName);
    ogs := FObj.OPCGroups;
    if idx <> -1
        then begin
            g := ogs.Item(idx); // HERE I GOT:  The parameter is incorrect
            Result := g;
        end;
end;

So it is interesting: the IndexOfGroup with same call is working, the GetGroupByName is not... :-(

So I determined I do not continue my fighting with windmills (Don Q).
I got TLB from a dear user that have Delphi7 (in Win7 the Delphi6 cannot produce OLE interface), and I found Kassl.

May these interfaces can help me...

Thanks:
    dd

Body:
As far as I know the constant and the strings are all converted to an OleString/BSTR (WideString). But since you are having these problems... probably not.

What does the documentation of OPCGroups.Add say? What is expected?

Do you have a type library? Maybe you can import them and use the interface directly.

Edit:

The documentation isn't very clear.

There are a few things you can try:

Check in CPU view what the Delphi compiler made of the code with the constant, maybe you see some hints there about what to do with your strings.

Try this code.

code:

const
  OPC_GROUP_NAME: WideString = 'MONKEY_C';
<...>
  g := r.OPCGroups.Add(OPC_GROUP_NAME);
  Log('Name ' + g.Name);

When above code works, try this:

const
{$J+} //writable constants on
  OPC_GROUP_NAME: WideString = 'dummy';
{$J-}
<...>
  OPC_GROUP_NAME := 'MONKEY_BLA';
  g := r.OPCGroups.Add(OPC_GROUP_NAME);
  Log('Name ' + g.Name); //should be: 'Name MONKEY_BLA'

Note: I don't like step 2, but if it works.. why not. To me it seems like there is a bug in the com-library you use.

Edit2:

I looked at the code generated by using the constant and using a normal string. With the constant I see the address of the first character being pushed on the stack, with the string I see the address of a pointer to a string being pushed on the stack.

With the code below I can simulate the same behaviour as with the constant:

var
  lWideArray: array[0..40] of WideChar;
  s: string;
  i: Integer;
<..>
s := 'MONKEY_FOO';
for i := 0 to Length(lWideArray) - 1 do
begin
  if i < Length(s) then
    lWideArray[i] := WideChar(s[i+1])
  else
    lWideArray[i] := #0;
end;

g := r.OPCGroups.Add(WideString(lWideArray));
Log('Name ' + g.Name);


问:
What is web service composition?
What exactly is web service composition?</p>

答:
Some web services which are provided for clients are abstract and composition of some smaller web services and it's called web service composition.

Sometimes there are more than one web service in order to use as the mentioned small web services, so we choose them based on QoS (Quality of Service) and many researches have been done on this subject.

Title: What is web service composition?


问:
Azure BotFramework
I was I asked to create this post.  I am using the bot service on azure.  I created a bot and everything worked great.  Then I deleted the bot and created a new on and now I get Microsoft App ID is not a valid GUID.  This happens when I hit the create bot button.  Thank you for all your help.</p>

答:
The App Id is a Guid that corresponds to your bot's App Id in dev.botframework.net  The App Name is different.  It looks like you've got your App Name (Bot handle, or Bot Id) in place of your App Id on the Bot Service Create blade.

This is your App Id:

Title: Azure BotFramework


问:
How can I italicise a certain word (which occurs multiple times) in my string in Swift?
I have a text that reads "Hello world. The world is so beautiful." I want to change it to "Hello world. The world is so beautiful."

I tried the following code but it only changes the first word.

```<code> let string : NSString =  "Hello world. The world is so beautiful."
 let attributedString = NSMutableAttributedString(string: string! as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
 let italicFontAttribute = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 17.0)]
 attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))
</code>```

答:
```<code>attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))
attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "World")))
</code>```

try this capital and small Charter both find in string.

Body:
I have a text that reads "Hello world. The world is so beautiful." I want to change it to "Hello world. The world is so beautiful."

I tried the following code but it only changes the first word.

 let string : NSString =  "Hello world. The world is so beautiful."
 let attributedString = NSMutableAttributedString(string: string! as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
 let italicFontAttribute = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 17.0)]
 attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))

Body:
attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))
attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "World")))

try this capital and small Charter both find in string.


问:
Azure interal loadbalancer using 2 different frontend IP's
I want to access my VM (the SQL Server instance to be specific) via 2 different IP addresses, one for internal use and one specific IP requested by a client that they will use. In my virtual network I need 2 different address spaces because the IP's are far apart. I also need 2 subnets then as far as I know (subnet A and subnet B).

In my internal load balancer I added both IP's (in different subnets) as frontend IP's, and added a rule to forward the traffic to my SQL Server VM instance (which is in subnet A). The rules are for different ports, but SQL Server is listening on both ports so the port thing works.

However...I can't connect via the 2nd (client requested IP), even if I switch the ports around, so it is the IP itself that's causing issues, perhaps because it is in subnet B and the VM is in subnet A? that would make sense because the first IP that is in the address space of subnet A does work?

In my load balancer rule I can specify the target VM and network adapater for both rules, so I would think the 2 subnets wouldn't be a problem.

My configuration -------

1 (internal) loadbalancer:

frontend IP's:

```<code> 10.4.2.250 (in subnet A, and addressspace 1)
 172.4.2.1 (in subnet B, and addressspace 2)
</code>```

Backendpools (1 pool):

```<code>1 VM, in subnet A
</code>```

Healthprobes (1 probe):

```<code>1 probe, TCP port 1440
</code>```

Load balancing rules:

```<code>TCP 1440 to backendpool port 1440 with probe 1440
TCP 1450 to backendpool port 1450 with probe 1440
</code>```

My MSSQL instance is configured via the Sql Server Configuration Manager > SQL Server Network Configuration > Protocols for MyInstance > TCP/IP properties

```<code>  Protocol -> Enabled = Yes, Listen All = Yes

  IP Addresses -> for all fields with 'TCP Port' = 1440,1450
</code>```

答:
According to your description, we can use internal load balancer to add two internal IP addresses to one VM.

However...I can't connect via the 2nd (client requested IP)as frontend IP's, and added a rule to forward the traffic to my SQL Server VM instance (which is in subnet A). The rules are for different ports, but SQL Server is listening on both ports so the port thing works

All the VMs in the same Vnet?  you create a internal load balancer, so all VMs should in the same Vnet, only in the same Vnet, other VM can communicate with the internal load balancer.

The SQL server is listening on bouth ports so the port thing works.

Have you configure it correctly? maybe we should test it. create a VM in the same Vnet with SQL Server, then use this VM to connect SQL Server with different ports. if it works, it means we should check load balancer configure, or we will check the SQL server port settings.

About internal Load balancer, we can add multiple frontend IP addresses(same Vnet, different subnets) in it.

In my test, I configure a web server on it, and listening on two ports (80 and 8080), I add two internal IP addresses in it:

frontend IP pool: sub1 10.0.1.5  sub2  10.0.2.9

backend pools:  VM1  10.0.1.4

Health probes:  TCP port 80

Load balancer rules:

1.sub1  front IP address 10.0.1.5  port 80

2.sub2  front IP address 10.0.2.9  port 8080

Then I create a VM in subnet2, and test the internal load balancer, with different frontend IP addresses with different ports, it works for me.

Body:
I want to access my VM (the SQL Server instance to be specific) via 2 different IP addresses, one for internal use and one specific IP requested by a client that they will use. In my virtual network I need 2 different address spaces because the IP's are far apart. I also need 2 subnets then as far as I know (subnet A and subnet B).

In my internal load balancer I added both IP's (in different subnets) as frontend IP's, and added a rule to forward the traffic to my SQL Server VM instance (which is in subnet A). The rules are for different ports, but SQL Server is listening on both ports so the port thing works.

However...I can't connect via the 2nd (client requested IP), even if I switch the ports around, so it is the IP itself that's causing issues, perhaps because it is in subnet B and the VM is in subnet A? that would make sense because the first IP that is in the address space of subnet A does work?

In my load balancer rule I can specify the target VM and network adapater for both rules, so I would think the 2 subnets wouldn't be a problem.

My configuration -------

1 (internal) loadbalancer:

frontend IP's:

 10.4.2.250 (in subnet A, and addressspace 1)
 172.4.2.1 (in subnet B, and addressspace 2)

Backendpools (1 pool):

1 VM, in subnet A

Healthprobes (1 probe):

1 probe, TCP port 1440

Load balancing rules:

TCP 1440 to backendpool port 1440 with probe 1440
TCP 1450 to backendpool port 1450 with probe 1440

My MSSQL instance is configured via the Sql Server Configuration Manager > SQL Server Network Configuration > Protocols for MyInstance > TCP/IP properties

  Protocol -> Enabled = Yes, Listen All = Yes

  IP Addresses -> for all fields with 'TCP Port' = 1440,1450


问:
android studio how to import custom java class from other module(package)?
i'm trying to use opensource android project

https://github.com/ksoichiro/Android-ObservableScrollView

so i cloned library module(there exist ObservableGridView, ...)

but i can't import that libraries... i don't know what is is and how to do. please help me.

but... i don't know how can i show my problem. i'm working in develop company so this code should not be shown...

答:
Try

Go to File -> New Module, a new dialog 'Create New Model' will be opened

Select 'Import Gradle project'

Press Next button

Select source directory

Finish


问:
Pygame error: display surface quit: Why?
Can anyone tell me why my app quits with:

pygame error: display Surface quit.

答: I had similar problem and discovered that Surface objects don't like to be deepcopied. When I used copy.deepcopy() on such object and then accessed the copy, I got that strange error message (without calling pygame.quit()). Maybe you experience similar behavior?</p>


问:
Java comparing two arrays and checking if the First array is consecutive of the Second
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.</p>

```<code> public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}
</code>```

答:
```<code>     int[] arrayA = {7,14,21,28};
     int[] arrayB = {1,3,5,7,14,21,28,32};
     boolean result=false;

     for(int i=0;i<arrayB.length;i++){

         if(arrayA[0] == arrayB[i]){
             for(int j=0;j<arrayA.length;j++){
                 if(arrayA[j] == arrayB[i+j]){
                     result=true;
                 }
                 else{
                     result=false;
                 }
             }
         }
     }
    System.out.println(result);
</code>```

Updated One:

```<code>public class Test {

public static void main(String[] args) {

    int[] arrayA = { 7, 14, 21, 28 };
    int[] arrayB = { 1, 3, 5, 7, 14, 21, 28, 32, 7 };
    boolean output = Test.appearsConsecutive(arrayA,arrayB);
    System.out.println(output);
}

public static boolean appearsConsecutive(int[] arrayA, int[] arrayB) {

    boolean result = false;

    for (int i = 0; i < arrayB.length; i++) {

        if (arrayA[0] == arrayB[i]) {
            for (int j = 0; j < arrayA.length; j++) {
                if (arrayA[j] == arrayB[i + j]) {
                    result = true;
                    break;
                } else {
                    result = false;
                }
            }
        }
    }
    System.out.println(result);
    return result;

}

}
</code>```

See above example.

Body:
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.

 public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}

Body:
     int[] arrayA = {7,14,21,28};
     int[] arrayB = {1,3,5,7,14,21,28,32};
     boolean result=false;

     for(int i=0;i<arrayB.length;i++){

         if(arrayA[0] == arrayB[i]){
             for(int j=0;j<arrayA.length;j++){
                 if(arrayA[j] == arrayB[i+j]){
                     result=true;
                 }
                 else{
                     result=false;
                 }
             }
         }
     }
    System.out.println(result);

Updated One:

public class Test {

public static void main(String[] args) {

    int[] arrayA = { 7, 14, 21, 28 };
    int[] arrayB = { 1, 3, 5, 7, 14, 21, 28, 32, 7 };
    boolean output = Test.appearsConsecutive(arrayA,arrayB);
    System.out.println(output);
}

public static boolean appearsConsecutive(int[] arrayA, int[] arrayB) {

    boolean result = false;

    for (int i = 0; i < arrayB.length; i++) {

        if (arrayA[0] == arrayB[i]) {
            for (int j = 0; j < arrayA.length; j++) {
                if (arrayA[j] == arrayB[i + j]) {
                    result = true;
                    break;
                } else {
                    result = false;
                }
            }
        }
    }
    System.out.println(result);
    return result;

}

}

See above example.


问:
Ruby Jekyll plug-in: undefined method '-@' for :flatify:Symbol
I'm getting the following error when attempting to build my Jekyll site:

```<code>jekyll 3.4.0 | Error: undefined method '-@' for :flatify:Symbol
</code>```

I believe this is due to a plug-in I'm trying to use, as I can build when I remove the file from my plugins directory. The code for the plug-in is as follows:

```<code>---
---

module Jekyll
  module ExpandNestedVariableFilter
    def flatify(input)
      Liquid::Template.parse(input).render(@context)
    end
  end
end

Liquid::Template.register_filter(Jekyll::ExpandNestedVariableFilter)
</code>```

答: You don't need those FrontMatter Dashes at the beginning. The bug could be because Jekyll 'processes' all files with ---\n---\n

Body:
I'm getting the following error when attempting to build my Jekyll site:

jekyll 3.4.0 | Error: undefined method '-@' for :flatify:Symbol

I believe this is due to a plug-in I'm trying to use, as I can build when I remove the file from my plugins directory. The code for the plug-in is as follows:

---
---

module Jekyll
  module ExpandNestedVariableFilter
    def flatify(input)
      Liquid::Template.parse(input).render(@context)
    end
  end
end

Liquid::Template.register_filter(Jekyll::ExpandNestedVariableFilter)


问:
PHP global variables null inside function if not already defined
It's been several years since I've messed with PHP. But now I'm trying to do phpBB Sessions Integration following this guide: phpBB Sessions Integration. The thing is, it won't work unless I go and define all the globals the phpBB app needs because they end up being null at runtime inside the functions.

So the code in the linked guide only works when I add this line of php code above it:

```<code>global $_SID, $auth, $cache, $config, $db, $phpbb_root_path, $phpEx, $SID, $template, $user;
</code>```

This isn't optimal since I'll have to keep updating this global declaration each time a new global variable is introduced into the phpBB codebase. :( Is there some kind of php ini setting that I should tweak or something to make it to where I don't have to declare these?

答:
This was how PHP worked :-) This guide is outdated. It was posted Oct 08, 2007. I am agree with you, using global variable is not optimal. I don't have solution, you have to declare these in each function (and protect your variables). If solutions existed, the community would use them. Some contributors purpose to package all of them in a super variable. But it was rejected (too dangerous, too slow, etc.)

Are you still using php3.0 ? If you want to improve the quality of code, you should upgrade your forum to version 3.2. The new system (using extensions) is very good and based on Symfony's Dependancy Injection.

Here is the guide to explain extension.

It is a bit complex to understand, so here is a very good extension to use in development environment.

Install it and follow steps to get a "skeleton code". You only have to edit it to implement your model.

Body:
It's been several years since I've messed with PHP. But now I'm trying to do phpBB Sessions Integration following this guide: phpBB Sessions Integration. The thing is, it won't work unless I go and define all the globals the phpBB app needs because they end up being null at runtime inside the functions.

So the code in the linked guide only works when I add this line of php code above it:

global $_SID, $auth, $cache, $config, $db, $phpbb_root_path, $phpEx, $SID, $template, $user;

This isn't optimal since I'll have to keep updating this global declaration each time a new global variable is introduced into the phpBB codebase. :( Is there some kind of php ini setting that I should tweak or something to make it to where I don't have to declare these?


问:
Drive Wordpress through external RSS
Is there any way to add RSS feeds to Wordpress itself, and have Wordpress merge your posts with the ones from the RSS feed and display them as if they were posts on the blog itself?

More importantly, the external feeds must be present in the final RSS feed provided by Wordpress.

Ideally, I would like to setup a category in Wordpress, define a URL, and have that category driven by the external RSS feed.

答:
Here is a tutorial i wrote for this exact thing on one of my project : http://www.script-tutorials.com/importing-multiple-rss-feeds-using-newswidget-jquery/
Mainly its a multiple site's rss mixer/combiner. and it can be used as your idea by adding your site's rss in it as well. you can display post excerpts order by date of publishing etc. </p>

Title: Drive Wordpress through external RSS


问:
How to display default parameters in the page URL in php?
I have created the php page named sample.php.I have used get method to get parameter values.

If no parameters passed from any pages get method uses default values.

```<code>if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
}
</code>```

Other pages in my project has the hyperlink to link to this page

.

I would like to display those default parameters in the URL even if no parameters passed from other pages.

```<code>http:\\localhost\myproj\sample.php?name="nithya"&id=1
</code>```

答:
@Nithya try it like below:</p>

```<code> //Sample.html

    <form id="myForm" method="get" action="sample.php">

            Name:<input type="text" name="name"><br>
            Id:<input type="text" name="id"><br>
            <input name="Submit" type="submit" class="button" value="Send">

    </form>

    //Sample.php

    <?php
    if(!empty($_GET["Submit"])){
        if(empty($_GET["name"]) && empty($_GET["id"])){
            header('Location: http:\\localhost\myproj\sample.php?name="nithya"&id=1');
        }
    }
?>
</code>```

Body:
I have created the php page named sample.php.I have used get method to get parameter values.

If no parameters passed from any pages get method uses default values.

if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
}

Other pages in my project has the hyperlink to link to this page

.

I would like to display those default parameters in the URL even if no parameters passed from other pages.

http:\\localhost\myproj\sample.php?name="nithya"&id=1

Body:
@Nithya try it like below:

 //Sample.html

    <form id="myForm" method="get" action="sample.php">

            Name:<input type="text" name="name"><br>
            Id:<input type="text" name="id"><br>
            <input name="Submit" type="submit" class="button" value="Send">

    </form>

    //Sample.php

    <?php
    if(!empty($_GET["Submit"])){
        if(empty($_GET["name"]) && empty($_GET["id"])){
            header('Location: http:\\localhost\myproj\sample.php?name="nithya"&id=1');
        }
    }
?>


答:
You need to do group by hearly and take the difference of time max minus min.</p>

```<code>select HOUR(tracking_dt_time),
(TIME_TO_SEC(max(tracking_dt_time))-TIME_TO_SEC(min(tracking_dt_time)))/60 as minutes from tracking_dtls group by HOUR(tracking_dt_time)
</code>```

Title: mysql calculate total minutes in perticular hours

Body:
i have a data like

    2017-03-22 10:57:01
    2017-03-22 10:57:09
    2017-03-22 10:59:35
    2017-03-22 10:59:55
    2017-03-22 11:00:01
    2017-03-22 11:08:16
    2017-03-22 11:39:07
    2017-03-22 11:50:37
    2017-03-22 11:59:57
   ..........
ex. 10 AM total minutes worked 45

    tracking_dtls

  device_id    tracking_dt_time
        1        2017-03-22 10:57:01
        1        2017-03-22 10:57:09
        1        2017-03-22 10:59:35
        1        2017-03-22 10:59:55
        1        2017-03-22 11:00:01
        1        2017-03-22 11:08:16
        1        2017-03-22 11:39:07
        1        2017-03-22 11:50:37
        1        2017-03-22 11:59:57

From tracking_dtls  table calculate total working minutes for a all hours

In this data calculate working minutes for all hours seprately.how can i do that can somebody please help me.

Body:
You need to do group by hearly and take the difference of time max minus min.

select HOUR(tracking_dt_time),
(TIME_TO_SEC(max(tracking_dt_time))-TIME_TO_SEC(min(tracking_dt_time)))/60 as minutes from tracking_dtls group by HOUR(tracking_dt_time)


问:
PHPUnit cannot mock __get function on mock object
I am trying to mock a mysqli object for my unit testing and therefore I have to either mock the property mysqli_result::__get() or mock the property mysqli_result::num_rows directly.
I already looked for a solution but the answers I found were just not working.

My Code looks like this:

```<code>use PHPUnit\Framework\TestCase;

class Mocks extends TestCase{
    public function makeMysqliMock(array $queries): mysqli{
        // build mocked mysqli-object
        #$link = $this
        #   ->getMockBuilder("mysqli")
        #   // set methods
        #   ->setMethods(['__get', "query", "real_escape_string"])
        #   ->getMock();
        $link = $this->createMock("mysqli");
        // set method 'real_escape_string'
        $link->expects($this->any())
            ->method("real_escape_string")
            ->will($this->returnCallback(function($str){
                return addslashes($str);
            }));
        // set method 'query'
        $link->expects($this->any())
            ->method("query")
            ->will($this->returnCallback(function(string $query) use ($queries){
                // pick the query result for the current test
                $data = isset($queries[$query]) ? $queries[$query] : null;
                // build mocked 'mysqli_result'
                if (is_array($data)){
                    $result = $this
                        ->getMockBuilder("mysqli_result")
                        ->setMethods(["fetch_assoc", "__get"])
                        ->disableOriginalConstructor()
                        ->getMock();
                    // build simulated fetch method
                    $result->expects($this->any())
                        ->method("fetch_assoc")
                        ->withAnyParameters()
                        ->will($this->returnCallback(function() use ($data){
                            // set internal result pointer
                            static $index = 0;
                            // return current result - increment pointer
                            return isset($data[$index]) ? $data[$index++] : false;
                        }));
                    $result->expects($this->at(0))
                        ->method("__get")
                        ->with($this->equalTo("mysqli_num_rows"))
                        ->will($this->returnValue(count($data)));

                    return $result;
                }else {
                    return is_null($data) ? false : 1;
                }
            }));
        return $link;
    }
}
</code>```

When I run that code phpunit gives me the following error message:

C:\xampp\htdocs\werimanage\php>php phpunit-6.0.11.phar tests
  PHPUnit 6.0.11 by Sebastian Bergmann and contributors.

PHP Fatal error:  Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

Fatal error: Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

So I do not know what the error is or how to fix it. I would really appreciate your help. Thanks!

答:
This error happens because magic method __get must accept one parameter -- the name of the property. When PHPUnit generates the code to declare the mock it uses the declaration of the method from the original class. Since there is no method __get declared for mysqli_result PHPUnit mock generator declares it as __get() without parameters, and this is encountered as error.

If you really want to do your coding and testing the way you do it, you can use the following approach:

```<code>class SuperMock extends mysqli_result {
    public function __get($name){

    }
}

class Mocks extends PHPUnit_Framework_TestCase
{
    public function testGet()
    {
        $data = ['one' => 1, 'two' => 2];
        $mock = $this->getMockBuilder('SuperMock')
                     ->disableOriginalConstructor()
                     ->setMethods(['__get', 'fetch_assoc'])
                     ->getMock();
        $mock->expects($this->once())
             ->method('__get')
             ->with('nonexistent')
             ->willReturn(42);
        $mock->expects($this->once())
             ->method('fetch_assoc')
             ->willReturn($data);
        $this->assertInstanceOf('mysqli_result', $mock);
        $this->assertSame(42, $mock->nonexistent);
        $this->assertSame($data, $mock->fetch_assoc());
    }

    public function testDirectProperty(){
        $mock = $this->getMockBuilder('SuperMock')
                     ->disableOriginalConstructor()
                     ->setMethods(['__get', 'fetch_assoc'])
                     ->getMock();
        $mock->nonexistent = 42;
        $this->assertSame(42, $mock->nonexistent);
    }
}
</code>```

This will technically solve the issue. Still I would suggest revising your testing strategy. Because now it looks like you are testing how the interaction with a database is performed. But do you really need to test if data is fetched as an associative array, and that number of rows is figured out through mysqli_num_rows property? Going this way makes tests too much coupled to the production code. I believe this is the case when it is more suffucient to test the result being retrieved rather than the internal details of this process.

Body:
I am trying to mock a mysqli object for my unit testing and therefore I have to either mock the property mysqli_result::__get() or mock the property mysqli_result::num_rows directly.
I already looked for a solution but the answers I found were just not working.

My Code looks like this:

use PHPUnit\Framework\TestCase;

class Mocks extends TestCase{
    public function makeMysqliMock(array $queries): mysqli{
        // build mocked mysqli-object
        #$link = $this
        #   ->getMockBuilder("mysqli")
        #   // set methods
        #   ->setMethods(['__get', "query", "real_escape_string"])
        #   ->getMock();
        $link = $this->createMock("mysqli");
        // set method 'real_escape_string'
        $link->expects($this->any())
            ->method("real_escape_string")
            ->will($this->returnCallback(function($str){
                return addslashes($str);
            }));
        // set method 'query'
        $link->expects($this->any())
            ->method("query")
            ->will($this->returnCallback(function(string $query) use ($queries){
                // pick the query result for the current test
                $data = isset($queries[$query]) ? $queries[$query] : null;
                // build mocked 'mysqli_result'
                if (is_array($data)){
                    $result = $this
                        ->getMockBuilder("mysqli_result")
                        ->setMethods(["fetch_assoc", "__get"])
                        ->disableOriginalConstructor()
                        ->getMock();
                    // build simulated fetch method
                    $result->expects($this->any())
                        ->method("fetch_assoc")
                        ->withAnyParameters()
                        ->will($this->returnCallback(function() use ($data){
                            // set internal result pointer
                            static $index = 0;
                            // return current result - increment pointer
                            return isset($data[$index]) ? $data[$index++] : false;
                        }));
                    $result->expects($this->at(0))
                        ->method("__get")
                        ->with($this->equalTo("mysqli_num_rows"))
                        ->will($this->returnValue(count($data)));

                    return $result;
                }else {
                    return is_null($data) ? false : 1;
                }
            }));
        return $link;
    }
}

When I run that code phpunit gives me the following error message:

C:\xampp\htdocs\werimanage\php>php phpunit-6.0.11.phar tests
  PHPUnit 6.0.11 by Sebastian Bergmann and contributors.

PHP Fatal error:  Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

Fatal error: Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

So I do not know what the error is or how to fix it. I would really appreciate your help. Thanks!

Body:
This error happens because magic method __get must accept one parameter -- the name of the property. When PHPUnit generates the code to declare the mock it uses the declaration of the method from the original class. Since there is no method __get declared for mysqli_result PHPUnit mock generator declares it as __get() without parameters, and this is encountered as error.

If you really want to do your coding and testing the way you do it, you can use the following approach:

class SuperMock extends mysqli_result {
    public function __get($name){

    }
}

class Mocks extends PHPUnit_Framework_TestCase
{
    public function testGet()
    {
        $data = ['one' => 1, 'two' => 2];
        $mock = $this->getMockBuilder('SuperMock')
                     ->disableOriginalConstructor()
                     ->setMethods(['__get', 'fetch_assoc'])
                     ->getMock();
        $mock->expects($this->once())
             ->method('__get')
             ->with('nonexistent')
             ->willReturn(42);
        $mock->expects($this->once())
             ->method('fetch_assoc')
             ->willReturn($data);
        $this->assertInstanceOf('mysqli_result', $mock);
        $this->assertSame(42, $mock->nonexistent);
        $this->assertSame($data, $mock->fetch_assoc());
    }

    public function testDirectProperty(){
        $mock = $this->getMockBuilder('SuperMock')
                     ->disableOriginalConstructor()
                     ->setMethods(['__get', 'fetch_assoc'])
                     ->getMock();
        $mock->nonexistent = 42;
        $this->assertSame(42, $mock->nonexistent);
    }
}

This will technically solve the issue. Still I would suggest revising your testing strategy. Because now it looks like you are testing how the interaction with a database is performed. But do you really need to test if data is fetched as an associative array, and that number of rows is figured out through mysqli_num_rows property? Going this way makes tests too much coupled to the production code. I believe this is the case when it is more suffucient to test the result being retrieved rather than the internal details of this process.


问:
Firebase returns the entire database even with setting ref url
I am trying to setup Firebase's realtime database in my web app.

I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.

The code I have here is trying to determine if a key exists:

```<code>var ref = firebase.database().ref('cars/');

ref.once('value', function (snapshot) {
    if (snapshot.hasChild('toyota')) {
        alert('exists');
    } else {
        alert('does not exist');
    }
});
</code>```

This always displays the 'does not exist' dialog, so when I ran:

```<code>alert(JSON.stringify(snapshot));
</code>```

I realized that firebase was fetching everything.

Here is the structure of my database:

```<code>{
"users": {
    "uid": {
        "name": "John Doe",
        "balance": 500
    }
},
"cars": {
    "carid": {
        "name": "Name of Car",
        "cost": "250",
        "features": [
            "ac", "awd", "leather_seats"
        ]
    }
  }
}
</code>```

Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.

答:
Hey try using the child method to access your nodes

```<code>var ref = firebase.database().ref().child('/cars');
</code>```

Sorry there was some missing bits.

Body:
I am trying to setup Firebase's realtime database in my web app.

I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.

The code I have here is trying to determine if a key exists:

var ref = firebase.database().ref('cars/');

ref.once('value', function (snapshot) {
    if (snapshot.hasChild('toyota')) {
        alert('exists');
    } else {
        alert('does not exist');
    }
});

This always displays the 'does not exist' dialog, so when I ran:

alert(JSON.stringify(snapshot));

I realized that firebase was fetching everything.

Here is the structure of my database:

{
"users": {
    "uid": {
        "name": "John Doe",
        "balance": 500
    }
},
"cars": {
    "carid": {
        "name": "Name of Car",
        "cost": "250",
        "features": [
            "ac", "awd", "leather_seats"
        ]
    }
  }
}

Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.

Body:
Hey try using the child method to access your nodes

var ref = firebase.database().ref().child('/cars');

Sorry there was some missing bits.


问:
javascript check values are same or not within double quotes?
In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not

```<code>      var str= "0,1,-1";
</code>```

How to check this variable.

答:
The author wants to compare these 3 values. You most separate this variable with split:

```<code>var str= "0,1,-1",
arr = str.split(',');
</code>```

all are same or not ie, true are false compare this array with function every

```<code>     var str= "0,1,-1",
     arr = str.split(',');

    var res = arr.every(function (item) {
       return item == arr[0];
    })

    console.log(res);
</code>```

Body:
In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not

      var str= "0,1,-1";

How to check this variable.

Body:
The author wants to compare these 3 values. You most separate this variable with split:

var str= "0,1,-1",
arr = str.split(',');

all are same or not ie, true are false compare this array with function every

     var str= "0,1,-1",
     arr = str.split(',');

    var res = arr.every(function (item) {
       return item == arr[0];
    })

    console.log(res);


问:
Storing a "Users Online" list for a chat application (php/ajax)
I have several chat rooms. Currently, I store the list of chat users in a php variable. If a user enters or leaves the room, the user's name is added/removed from that list.
To make this storage persistent, I use memcached. To update the status of the chat room and send the user list to all users in the chat room, I use periodical ajax requests that fetch the user list into the browsers of the users who are in the chat.

It works okay. But I doubt that sending the whole list of chat users to everybody every XX seconds is a good idea if there are a couple of hundred people in the chat.

How are chat rooms usually dealing with this problem?

答:
Thanks for all the suggestions. Additionally, I will look into running a comet server.
The long-polling approach just would not scale well.</p>


问:
Reformatting map values and updating with spread syntax
I'm trying to format the object properties within an array. I'm having some trouble as The following code throws the following error but the react native throws  TypeError: In this environment the sources for assign MUST be an object.This error is a performance optimization and not spec compliant. <<< path/to/project/node_modules/react-native/packager/src/Resolver/polyfills/polyfills.js

```<code>const objArr = [
   { event.date: '2016-03-10T00:00:00', event.location: 'NV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'WV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'CA' }
],

const formatDate = (data) => {
  const formattedDate = moment(data['event.start_date']).format('DD MMM YYYY');

  return { ...data, data['event.start_date']: formattedDate } };
}

const formatDates = (arr) => { return _.map(arr, formatDate) }

let result = _.map(objArr, formatDates);
</code>```

How would i change the event.date to the formatted data without touching the rest of the object? In reality have many variables I would like to pass over, and don't think individually assigning each to a new object is best.

How should I go about this? Any help / tips appreciated!

答:
You seem to be grossly overcomplicating the task by using several maps.

If you simplify the problem, you should be able to do this:

```<code>const objArr = [
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'NV' },
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'WV' },
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'CA' }
];

const result = objArr.map((event) => ({
  ...event,
  'event.start_date': moment(event['event.start_date']).format('DD MMM YYYY'),
}));

console.log(result);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to format the object properties within an array. I'm having some trouble as The following code throws the following error but the react native throws  TypeError: In this environment the sources for assign MUST be an object.This error is a performance optimization and not spec compliant. <<< path/to/project/node_modules/react-native/packager/src/Resolver/polyfills/polyfills.js

const objArr = [
   { event.date: '2016-03-10T00:00:00', event.location: 'NV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'WV' },
   { event.date: '2016-03-10T00:00:00', event.location: 'CA' }
],

const formatDate = (data) => {
  const formattedDate = moment(data['event.start_date']).format('DD MMM YYYY');

  return { ...data, data['event.start_date']: formattedDate } };
}

const formatDates = (arr) => { return _.map(arr, formatDate) }

let result = _.map(objArr, formatDates);

How would i change the event.date to the formatted data without touching the rest of the object? In reality have many variables I would like to pass over, and don't think individually assigning each to a new object is best.

How should I go about this? Any help / tips appreciated!

Body:
You seem to be grossly overcomplicating the task by using several maps.

If you simplify the problem, you should be able to do this:

const objArr = [
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'NV' },
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'WV' },
  { 'event.date': '2016-03-10T00:00:00', 'event.location': 'CA' }
];

const result = objArr.map((event) => ({
  ...event,
  'event.start_date': moment(event['event.start_date']).format('DD MMM YYYY'),
}));

console.log(result);


问:
Using ngstorage for persistent data
I know that there are solutions  to how to use ngstorage in our applications to have persistent data available even after refresh. I tried implementing it for the first time in my form today. But unable to figure out where I am going wrong. Can someone please let me know where I am going wrong? Also, I am looking to have the persistent functionality on adding and deleting the data.

```<code>angular.module('myApp', ['ngStorage'])
  .controller('AppController', ['$scope', '$localStorage',
    '$sessionStorage',
    function($scope,$localStorage,$sessionStorage) {
      var self = this;

      self.$storage = $localStorage;

      self.user = {
        id: null,
        username: '',
        address: '',
        email: ''
      };
      self.id = 4;

      self.users = [{
        id: 1,
        email: 'sam@tarly.com',
        firstname: 'Sam',
        lastname: 'Tarly',
        telephone: 1234567890,
        address: 'NY',

      }, {
        id: 2,
        email: 'jon@snow.com',
        firstname: 'Jon',
        lastname: 'Snow',
        telephone: 9876543210,
        address: 'The Wall',
      }, {
        id: 3,
        email: 'dany@targaryen.com',
        firstname: 'Dany',
        lastname: 'Targaryen',
        telephone: 1234987650,
        address: 'NEBRASKA'
      }];

      self.submit = function() {
        if (self.user.id === null) {
          self.user.id = self.id++;
          alert('Added New User', self.user);
          self.users.push(self.user);
          $localStorage.users = self.users;
        } else {
          for (var i = 0; i < self.users.length; i++) {
            if (self.users[i].id === self.user.id) {
              self.users[i] = self.user;
              break;
            }
          }
          alert('User updated with id ', self.user.id);
        }
        self.reset();
      };

      self.edit = function(id) {
        alert('id to be edited', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.user = angular.copy(self.users[i]);
            break;
          }
        }
      };

      self.remove = function(id) {
        alert('id to be deleted', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.users.splice(i, 1);
            $localStorage.users = self.users;
            if (self.user.id === id) { //It is shown in form, reset it.
              self.reset();
            }
            break;
          }
        }
      };

      self.reset = function() {
        self.user = {
          id: null,
          username: '',
          address: '',
          email: ''
        };
        $scope.myForm.$setPristine(); //reset Form
      };

    }
    ]);
</code>```

Plnkr Link

答:
From my understanding, for you the issue is the value not shown in table after adding the data and refreshing the page. The problem is you are initially loading the data with static array value. The data is infact added to storage. You just have to call the initial loading from $localStorage. Just change the self.users = [{..}] to  self.users = $localStorage.users. I have updated the plunkr. Please take a look at it.

Plunkr

Title: Using ngstorage for persistent data

Body:
I know that there are solutions  to how to use ngstorage in our applications to have persistent data available even after refresh. I tried implementing it for the first time in my form today. But unable to figure out where I am going wrong. Can someone please let me know where I am going wrong? Also, I am looking to have the persistent functionality on adding and deleting the data.

angular.module('myApp', ['ngStorage'])
  .controller('AppController', ['$scope', '$localStorage',
    '$sessionStorage',
    function($scope,$localStorage,$sessionStorage) {
      var self = this;

      self.$storage = $localStorage;

      self.user = {
        id: null,
        username: '',
        address: '',
        email: ''
      };
      self.id = 4;

      self.users = [{
        id: 1,
        email: 'sam@tarly.com',
        firstname: 'Sam',
        lastname: 'Tarly',
        telephone: 1234567890,
        address: 'NY',

      }, {
        id: 2,
        email: 'jon@snow.com',
        firstname: 'Jon',
        lastname: 'Snow',
        telephone: 9876543210,
        address: 'The Wall',
      }, {
        id: 3,
        email: 'dany@targaryen.com',
        firstname: 'Dany',
        lastname: 'Targaryen',
        telephone: 1234987650,
        address: 'NEBRASKA'
      }];

      self.submit = function() {
        if (self.user.id === null) {
          self.user.id = self.id++;
          alert('Added New User', self.user);
          self.users.push(self.user);
          $localStorage.users = self.users;
        } else {
          for (var i = 0; i < self.users.length; i++) {
            if (self.users[i].id === self.user.id) {
              self.users[i] = self.user;
              break;
            }
          }
          alert('User updated with id ', self.user.id);
        }
        self.reset();
      };

      self.edit = function(id) {
        alert('id to be edited', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.user = angular.copy(self.users[i]);
            break;
          }
        }
      };

      self.remove = function(id) {
        alert('id to be deleted', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.users.splice(i, 1);
            $localStorage.users = self.users;
            if (self.user.id === id) { //It is shown in form, reset it.
              self.reset();
            }
            break;
          }
        }
      };

      self.reset = function() {
        self.user = {
          id: null,
          username: '',
          address: '',
          email: ''
        };
        $scope.myForm.$setPristine(); //reset Form
      };

    }
    ]);

Plnkr Link


问:
Keep a large string in memory
I have the following java code:

```<code>Path path = Paths.get("largefile.txt2");
if (Files.exists(path))
   exchange.getIn().setBody(Files.lines(path, Charset.forName("UTF-8")).map(row -> row + System.lineSeparator()).collect(Collectors.joining()).trim());
//OOM error!
</code>```

I essentially need to read the entire file in memory to do various regex processing and splitting based on some search critera. The files can be as large as 300 MB - 1GB large.

The problem I have as that this works for files around 100 MB but once it reaches 200 or more I get out of memory error at .setBody(..) related to heap size.

Is there a more efficient and especially less memory consuming approach? Memory is more important for me than speed. Or do I need to rethink my entire approach and read piece by piece?

答:
This will probably not help too much, maybe let you work with a file a little bigger. You're creating many more Strings then required, by using things like:

row + System.lineSeparator() and .trim() on the end. You can probably use a lot less memory by changing your code a bit to:

```<code>exchange.getIn().setBody(Files.lines(path, Charset.forName("UTF-8")).collect(Collectors.joining(System.lineSeparator()));
</code>```

Although I don't quite understand why you're reading the file line by line and then joining the lines once again with a line separator.

Also to process a large file with regex it maybe useful to use the Scanner class and use the Scanner's findWithinHorizon method with a sufficiently large horizon for your needs. The scanner will advance automatically as matches are retrieved.

Title: Keep a large string in memory

Body:
I have the following java code:

Path path = Paths.get("largefile.txt2");
if (Files.exists(path))
   exchange.getIn().setBody(Files.lines(path, Charset.forName("UTF-8")).map(row -> row + System.lineSeparator()).collect(Collectors.joining()).trim());
//OOM error!

I essentially need to read the entire file in memory to do various regex processing and splitting based on some search critera. The files can be as large as 300 MB - 1GB large.

The problem I have as that this works for files around 100 MB but once it reaches 200 or more I get out of memory error at .setBody(..) related to heap size.

Is there a more efficient and especially less memory consuming approach? Memory is more important for me than speed. Or do I need to rethink my entire approach and read piece by piece?

Body:
This will probably not help too much, maybe let you work with a file a little bigger. You're creating many more Strings then required, by using things like:

row + System.lineSeparator() and .trim() on the end. You can probably use a lot less memory by changing your code a bit to:

exchange.getIn().setBody(Files.lines(path, Charset.forName("UTF-8")).collect(Collectors.joining(System.lineSeparator()));

Although I don't quite understand why you're reading the file line by line and then joining the lines once again with a line separator.

Also to process a large file with regex it maybe useful to use the Scanner class and use the Scanner's findWithinHorizon method with a sufficiently large horizon for your needs. The scanner will advance automatically as matches are retrieved.


问:
Python: Extract single line from file
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

```<code>"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here
</code>```

My attempt at a script:

```<code>file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]
</code>```

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

答:
Although you're relatively new, you should start learning to use list comprehension, here is an example on how you can use it for your situation. I explained the details in the comments and the comments are matched to the corresponding order.

```<code>splitdata = [line.split() for line in file if line.startswith('#')]
# defines splitdata as a list because comprehension is wrapped in []
                          # make a for loop to iterate through file
                                           #checks if the line "startswith" a '#'
                                           # note: you should call functions/methods using the () not []
             # split the line at spaces if the if startment returns True
</code>```

Title: Python: Extract single line from file

Body:
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here

My attempt at a script:

file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

Body:
Although you're relatively new, you should start learning to use list comprehension, here is an example on how you can use it for your situation. I explained the details in the comments and the comments are matched to the corresponding order.

splitdata = [line.split() for line in file if line.startswith('#')]
# defines splitdata as a list because comprehension is wrapped in []
                          # make a for loop to iterate through file
                                           #checks if the line "startswith" a '#'
                                           # note: you should call functions/methods using the () not []
             # split the line at spaces if the if startment returns True