问:
Validation Of UserEmail Is not working in php
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

```<code><html>
<head><title>Insertion</title>

</head>
<body>
<style>

#colour {
text-decoration:none;
}
</style>
<div id="display">
<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="<table border='1' align='center'>";
$display.="<tr><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>ExpiryDate</th><th>RegistrationKey</th><th colspan='3'>Action</th></tr>";
while($result=mysql_fetch_array($query2))
{
$display.="<tr>";

$display.="<td>".$result['userName']."</td>";
$display.="<td>".$result['userEmail']."</td>";
$display.="<td>".$result['userPassword']."</td>";
$display.="<td>".$result['regDate']."</td>";
$display.="<td>".$result['expiry_date']."</td>";
$display.="<td>".$result['registration_key']."</td>";
$display.="<td><a id='colour' class='tooltip' title='Edit' href='user_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='user_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='insert' href='chapter_subscription_search.php?user_Id=".$result['userId']." '>i</a></td>";
$display.="</tr>";

$display.="</table>";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

<table align='center' border='1'>

    <tr>

           <td> <label for="userId">UserId</label></td>
            <td ><input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/></td>

        </tr>
        <tr>
        <td> <label for="userName">UserName</label></td>
        <td ><input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userEmail">UserEmail</label></td>
        <td ><input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userPassword">UserPassword</label></td>
        <td ><input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="expiry_date">ExpiryDate</label></td>
        <td ><input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
        </tr>

        </table>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query9))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";

echo $display;
}

?>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });

</script>

</body>
</html>
</code>```

答:
Besides the fact that you are using deprecated code to interact with MySQL, the record is being inserted because although the email validation is working correctly, the rest of the code is still being executed.

If you insert a die(); or redirect the user to an error page, the record will not be created.

```<code>$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
exit();
// Or add a redirection here
}
</code>```

Body:
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

<title>Insertion</title>

<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="
";
$display.="
UserName	UserEmail	UserPassword	RegDate	ExpiryDate	RegistrationKey	Action
";
while($result=mysql_fetch_array($query2))
{
$display.="
";

$display.="".$result['userName']."	";
$display.="".$result['userEmail']."	";
$display.="".$result['userPassword']."	";
$display.="".$result['regDate']."	";
$display.="".$result['expiry_date']."	";
$display.="".$result['registration_key']."	";
$display.="	";
$display.="	";

$display.="i	";
$display.="
";

$display.="
";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

            UserId
            <input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/>

         UserName
        <input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/>

         UserEmail
        <input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/>

         UserPassword
        <input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/>

         ExpiryDate
        <input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/>

         EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	Action
";
while($result=mysql_fetch_array($query9))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";

echo $display;
}

?>

Body:
Besides the fact that you are using deprecated code to interact with MySQL, the record is being inserted because although the email validation is working correctly, the rest of the code is still being executed.

If you insert a die(); or redirect the user to an error page, the record will not be created.

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
exit();
// Or add a redirection here
}


来源: stackexchange

问:
How do I split a list of array?
Here is the list array:

```<code>{"things":{"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}
</code>```

here is the code:

```<code>var t = things;
string aa = t[0].ToString();
</code>```

How do I split the above array in , separator and _ .
from the above array i want only 1_4,3_13...this column and save in two different var.

when I am using

```<code>string[] ss = aa.Split(new char[] { ',', '|', }, System.StringSplitOptions.RemoveEmptyEntries);
</code>```

the problem is that in first list {"things":{"1":"1_4".
comes

so how to remove {"things"??

答:
You should not parse JSON yourself. Do not reinvent the wheel.

You should define a class

```<code>public class MyClass
{
    [JsonProperty("things")]
    public Dictionary<int, string> Things { get; set; }
}
</code>```

Then deserialize your string into an instance of MyClass

```<code>var rawData = "{\"things\":{\"1\":\"1_4\",\"3\":\"3_13\",\"4\":\"4_18\",\"5\":\"5_25\",\"6\":\"6_28\",\"7\":\"7_32\"}}";
var data = JsonConvert.DeserializeObject<MyClass>(rawData);
</code>```

Then you can use data

```<code>Console.WriteLine(data.Things[1]);
</code>```

You should add Newtonsoft.Json Nuget package to your project and add using Newtonsoft.Json namespace to your code file.

ContentLicense: CC BY-SA 3.0

Title: How do I split a list of array?

Body:
Here is the list array:

{"things":{"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}

here is the code:

var t = things;
string aa = t[0].ToString();

How do I split the above array in , separator and _ .
from the above array i want only 1_4,3_13...this column and save in two different var.

when I am using

string[] ss = aa.Split(new char[] { ',', '|', }, System.StringSplitOptions.RemoveEmptyEntries);

the problem is that in first list {"things":{"1":"1_4".
comes

so how to remove {"things"??

Body:
You should not parse JSON yourself. Do not reinvent the wheel.

You should define a class

public class MyClass
{
    [JsonProperty("things")]
    public Dictionary<int, string> Things { get; set; }
}

Then deserialize your string into an instance of MyClass

var rawData = "{\"things\":{\"1\":\"1_4\",\"3\":\"3_13\",\"4\":\"4_18\",\"5\":\"5_25\",\"6\":\"6_28\",\"7\":\"7_32\"}}";
var data = JsonConvert.DeserializeObject<MyClass>(rawData);

Then you can use data

Console.WriteLine(data.Things[1]);

You should add Newtonsoft.Json Nuget package to your project and add using Newtonsoft.Json namespace to your code file.


问:
How to import GoogleAnalytics header into a library Framework?
I create a library framework for my project and I want the framework to be able to depend on Google Analytics library. How do I import the headers into the framework because unlike an app target, framework doesn't have a bridging header? And importing the Google Analytics headers inside the framework's public header file will give other unexpected errors (include of non-modular header inside framework module).</p>

答:
HI you can add  Pod of Google Analytics
then you can use of this in your app
 add pod click the link below and follow the steps.

https://developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift

Hope it helps.


问:
Find line count of a file in HDFS to compare with the count present in QC file
I have a data file and qc file loaded in HDFS and I want to compare the count present in QC file and the data file line count. For this, I wrote a shell script which extracts the count part of the QC file and does wc -l for Data file.

For QA file:

qccount=$(webhdfs -cat hdfs://${CLUSTER_NAME}$hdfs_src_path/$directory/$qc_file_name | cut -d "|" -f2)

echo "QC file count: $qccount";

This prints out the count as 256341

For data file:

file_count=$(webhdfs -cat hdfs://${CLUSTER_NAME}$hdfs_src_path/$directory/$data_file_name | wc -l | cut -d " " -f1)

echo "File count: $file_count";

This prints out 0

Here wc -l for the file in hdfs is not working may I know the reason?

答:
You should use something like this:

file_count=$(hdfs dfs -cat hdfs://${CLUSTER_NAME}$hdfs_src_path/$directory/$data_file_name | wc -l)

echo "File count: $file_count";

Note: I am not sure why you have used webhdfs -cat instead of hdfs dfs -cat


问:
How to Use stankevich-python puppet module?
I am writing a puppet manifest file to install python libraries through pip install.

This python module is installed on the server, link shown below https://forge.puppetlabs.com/stankevich/python

I've installed the module by doing

```<code>puppet module install stankevich-python
</code>```

Here is the manifest file I created in my sites.pp

```<code>class { 'python' :
    version           => 'system',
    pip               => 'present'
}
python::pip { 'reportlab' :
    pkgname         => 'reportlab',
    ensure          => latest,
}
</code>```

Errors on my agent state that 'python' resource could not be found

```<code>Error: Could not retrieve catalog from remote server: Error 500 on SERVER: {"message":"Server Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class python at /etc/puppetlabs/code/environments/production/manifests/site.pp:6:1 on node dev1","issue_kind":"RUNTIME_ERROR","stacktrace":["Warning: The 'stacktrace' property is deprecated and will be removed in a future version of Puppet. For security reasons, stacktraces are not returned with Puppet HTTP Error responses."]}
</code>```

However, I've verified my module is there,

```<code>$ puppet module list
/home/ubuntu/.puppetlabs/etc/code/modules
├── puppetlabs-stdlib (v4.16.0)
├── stahnma-epel (v1.2.2)
└── stankevich-python (v1.18.2)
</code>```

Any advice appreciated. Thanks.

答:
My bad. I need to run

```<code>puppet module install stankevich-python
</code>```

in root, which I didn't. After doing that it works.

Body:
I am writing a puppet manifest file to install python libraries through pip install.

This python module is installed on the server, link shown below https://forge.puppetlabs.com/stankevich/python

I've installed the module by doing

puppet module install stankevich-python

Here is the manifest file I created in my sites.pp

class { 'python' :
    version           => 'system',
    pip               => 'present'
}
python::pip { 'reportlab' :
    pkgname         => 'reportlab',
    ensure          => latest,
}

Errors on my agent state that 'python' resource could not be found

Error: Could not retrieve catalog from remote server: Error 500 on SERVER: {"message":"Server Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class python at /etc/puppetlabs/code/environments/production/manifests/site.pp:6:1 on node dev1","issue_kind":"RUNTIME_ERROR","stacktrace":["Warning: The 'stacktrace' property is deprecated and will be removed in a future version of Puppet. For security reasons, stacktraces are not returned with Puppet HTTP Error responses."]}

However, I've verified my module is there,

$ puppet module list
/home/ubuntu/.puppetlabs/etc/code/modules
├── puppetlabs-stdlib (v4.16.0)
├── stahnma-epel (v1.2.2)
└── stankevich-python (v1.18.2)

Any advice appreciated. Thanks.

Body:
My bad. I need to run

puppet module install stankevich-python

in root, which I didn't. After doing that it works.


问:
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>```

答:
The root cause serms to be the select that sets id_toko variable's value:

```<code>  SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  );
</code>```

In the select you inner join tbl_transaksi_detail (the table with the trigger in question) on another table. However, in the 1st case tbl_transaksi_detail is still empty (the trigger is before insert), therefore id_toko variable is set to null.

This will result q being null, which in turn results in the entire calculation set to null.

In the 2nd case there is already a record inserted into tbl_transaksi_detail table, therefore the calculation returns a non null value. But it returns the correct values only because the 1st and 2nd records' details are exactly the same.

I do not really understand that select that calculates id_toko anyway. If that is a transaction id, then you may use last_insert_id() if it is auto increment and the transaction record has just been created or max(id_toko) to get the highest value of id_toko (this is not multi user safe).

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:
The root cause serms to be the select that sets id_toko variable's value:

  SET
    id_toko =(
    SELECT DISTINCT
      `tbl_transaksi`.`id_toko`
    FROM
      `tbl_transaksi`,
      `tbl_transaksi_detail`
    WHERE
      `tbl_transaksi`.`no_transaksi` = no_trans
  );

In the select you inner join tbl_transaksi_detail (the table with the trigger in question) on another table. However, in the 1st case tbl_transaksi_detail is still empty (the trigger is before insert), therefore id_toko variable is set to null.

This will result q being null, which in turn results in the entire calculation set to null.

In the 2nd case there is already a record inserted into tbl_transaksi_detail table, therefore the calculation returns a non null value. But it returns the correct values only because the 1st and 2nd records' details are exactly the same.

I do not really understand that select that calculates id_toko anyway. If that is a transaction id, then you may use last_insert_id() if it is auto increment and the transaction record has just been created or max(id_toko) to get the highest value of id_toko (this is not multi user safe).


问:
Python csv.reader: How do I return to the top of the file?
When I'm moving through a file with a csv.reader, how do I return to the top of the file.   If I were doing it with a normal file I could just do something like "file.seek(0)".  Is there anything like that for the csv module?

Thanks ahead of time ;)

答:
You can seek the file directly. For example:</p>

```<code>>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> for row in c: print row   # again
['1', '2', '3']
['4', '5', '6']
</code>```

OwnerDisplayName: Casey

ContentLicense: CC BY-SA 2.5

Body:
You can seek the file directly. For example:

>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> for row in c: print row   # again
['1', '2', '3']
['4', '5', '6']

OwnerDisplayName: Federico Ramponi

LastEditorDisplayName: Federico Ramponi


问:
Using BroadcastReceiver to check Battery Level but App crash?
I am trying to get current battery level using broadcast receiver with intentfilter ACTION_BATTERY_CHANGED having only one TextView in my xml and setting its text property to some string+integer variable that should hold value of BatteryManager.EXTRA_LEVEL. But app crashes everytime it try to boot.
Am i missing something?

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
TextView tvcl=(TextView) findViewById(R.id.tvcl);

private BroadcastReceiver bcr=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int currentLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
        tvcl.setText("Current Battery Level "+ Integer.toString(currentLevel) + "%");
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    IntentFilter bcFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(bcr,bcFilter);
}
</code>```

}

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

答:
The line

```<code>TextView tvcl=(TextView) findViewById(R.id.tvcl);
</code>```

appears to be in the class definition and not in a method.
If so, then it will return null since the ContentView isn't set until OnCreate whereas this definition occurs at object creation time.

Body:
I am trying to get current battery level using broadcast receiver with intentfilter ACTION_BATTERY_CHANGED having only one TextView in my xml and setting its text property to some string+integer variable that should hold value of BatteryManager.EXTRA_LEVEL. But app crashes everytime it try to boot.
Am i missing something?

MainActivity.java

public class MainActivity extends AppCompatActivity {
TextView tvcl=(TextView) findViewById(R.id.tvcl);

private BroadcastReceiver bcr=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int currentLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
        tvcl.setText("Current Battery Level "+ Integer.toString(currentLevel) + "%");
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    IntentFilter bcFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(bcr,bcFilter);
}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Body:
The line

TextView tvcl=(TextView) findViewById(R.id.tvcl);

appears to be in the class definition and not in a method.
If so, then it will return null since the ContentView isn't set until OnCreate whereas this definition occurs at object creation time.


问:
multithreading in java to print abc using 3 threads
the task is to print abc repeatedly using three threads infinite number of times
my code is

```<code>package javap;

public class Pattern {

    volatile int status=1;
    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a=new A1(p);
        B1 b=new B1(p);
        C1 c=new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    Pattern p1;

    A1(Pattern p){
        this.p1 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p1) {

                for (int i = 0; i < 100; i++) {

                    while(p1.status!=1){
                        p1.wait();
                    }

                    System.out.print("A ");
                    p1.status = 2;
                  p1.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    Pattern p2;

    B1(Pattern p2){
        this.p2 = p2;
    }

    @Override
    public void run() {

        try{
            synchronized (p2) {

                for (int i = 0; i < 100; i++) {

                    while(p2.status!=2){
                        p2.wait();
                    }

                    System.out.print("B ");
                    p2.status = 3;
                   p2.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    Pattern p3;

    C1(Pattern p){
        this.p3 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p3) {

                for (int i = 0; i < 100; i++) {

                    while(p3.status!=3){
                       p3.wait();
                    }

                    System.out.print("C ");
                    p3.status = 1;
                   p3.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}
</code>```

when i tried using for(;;) or while(true) my ide hangs and i am nt getting any output
so i restricted it to 100 times.
is there anyway that i can make this run infinite number of times.

thanks in advance

答:
Your code seems fine.  That said, it seems you are writing too much code to achieve your goal... Consider using Executors.newFixedThreadPool(3) to create your 3 threads and put them in a pool.

```<code>ExecutorService service = Executors.newFixedThreadPool(3);
</code>```

Then, Pass a task to the pool (A Callable)

```<code>Future<String> resultA = service.submit(() -> {
    System.out.print("A ");
    return "A";
});
</code>```

Now wait for the task to finish before passing the next task:

```<code>resultA.get();
</code>```

Here is a full code snippet:

```<code>public static void main(String[] args) throws ExecutionException, InterruptedException {

    ExecutorService service = Executors.newFixedThreadPool(3);
    int x = 0;
    while (x < 100) {
        service.submit(() -> {
            System.out.print("A ");
            return "A";
        }).get();

        service.submit(() -> {
            System.out.print("B ");
            return "B";
        }).get();

        service.submit(() -> {
            System.out.print("C ");
            return "C";
        }).get();

        x++;
    }

    service.shutdown();
}
</code>```

That said you can remove all the Repeating code using:

```<code>public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService service = Executors.newFixedThreadPool(3);
        int x = 0;
        while (x < 100) {
            service.submit(getTask("A ")).get();
            service.submit(getTask("B ")).get();
            service.submit(getTask("C ")).get();
            x++;
        }

        service.shutdown();
    }

    private static Callable<String> getTask(String task) {
        return () -> {
            System.out.print(task);
            return task;
        };
    }
}
</code>```

note that main must not throw exceptions, but that should be obvious.

Also,  @Elliott Frisch answer is awesome as it uses JAVA 8 parallel streams.
 I think you are trying to learn about Threads so my answer uses the Executors API which Makes Thread related code much shorter and concise.

One should be familiar with both Streams and Executors.

Body:
the task is to print abc repeatedly using three threads infinite number of times
my code is

package javap;

public class Pattern {

    volatile int status=1;
    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a=new A1(p);
        B1 b=new B1(p);
        C1 c=new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    Pattern p1;

    A1(Pattern p){
        this.p1 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p1) {

                for (int i = 0; i < 100; i++) {

                    while(p1.status!=1){
                        p1.wait();
                    }

                    System.out.print("A ");
                    p1.status = 2;
                  p1.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    Pattern p2;

    B1(Pattern p2){
        this.p2 = p2;
    }

    @Override
    public void run() {

        try{
            synchronized (p2) {

                for (int i = 0; i < 100; i++) {

                    while(p2.status!=2){
                        p2.wait();
                    }

                    System.out.print("B ");
                    p2.status = 3;
                   p2.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    Pattern p3;

    C1(Pattern p){
        this.p3 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p3) {

                for (int i = 0; i < 100; i++) {

                    while(p3.status!=3){
                       p3.wait();
                    }

                    System.out.print("C ");
                    p3.status = 1;
                   p3.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}

when i tried using for(;;) or while(true) my ide hangs and i am nt getting any output
so i restricted it to 100 times.
is there anyway that i can make this run infinite number of times.

thanks in advance

Body:
Your code seems fine.  That said, it seems you are writing too much code to achieve your goal... Consider using Executors.newFixedThreadPool(3) to create your 3 threads and put them in a pool.

ExecutorService service = Executors.newFixedThreadPool(3);

Then, Pass a task to the pool (A Callable)

Future<String> resultA = service.submit(() -> {
    System.out.print("A ");
    return "A";
});

Now wait for the task to finish before passing the next task:

resultA.get();

Here is a full code snippet:

public static void main(String[] args) throws ExecutionException, InterruptedException {

    ExecutorService service = Executors.newFixedThreadPool(3);
    int x = 0;
    while (x < 100) {
        service.submit(() -> {
            System.out.print("A ");
            return "A";
        }).get();

        service.submit(() -> {
            System.out.print("B ");
            return "B";
        }).get();

        service.submit(() -> {
            System.out.print("C ");
            return "C";
        }).get();

        x++;
    }

    service.shutdown();
}

That said you can remove all the Repeating code using:

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService service = Executors.newFixedThreadPool(3);
        int x = 0;
        while (x < 100) {
            service.submit(getTask("A ")).get();
            service.submit(getTask("B ")).get();
            service.submit(getTask("C ")).get();
            x++;
        }

        service.shutdown();
    }

    private static Callable<String> getTask(String task) {
        return () -> {
            System.out.print(task);
            return task;
        };
    }
}

note that main must not throw exceptions, but that should be obvious.

Also,  @Elliott Frisch answer is awesome as it uses JAVA 8 parallel streams.
 I think you are trying to learn about Threads so my answer uses the Executors API which Makes Thread related code much shorter and concise.

One should be familiar with both Streams and Executors.


问:
Create a parent-child relationship after the parent type already exists
I'm trying to add a new type as a child of an existing type. From ElasticSearch documentation, it looks like this is possible but there is no details about how to do it.

Here's what the documentation says:

This must be done at index creation time, or with the update-mapping API before the child type has been created.

There are no details about setting up a parent-child relationship in the update-mapping API documentation.

Intuitively, I think a parent-child relationship should be allowed to be established after a parent already exists since the parent does not need to know anything about the child.

Here's the error I'm getting when I create a new type as a child:

```<code>{
"error": {
  "root_cause": [
    {
      "type": "illegal_argument_exception",
      "reason": "can't add a _parent field that points to an already existing type"
    }
  ],
  "type": "illegal_argument_exception",
  "reason": "can't add a _parent field that points to an already existing type"
},
"status": 400
}
</code>```

答: This is not allowed in ElasticSearch, so it mandates to create both parent and child in the same request or call.</p>

Body:
I'm trying to add a new type as a child of an existing type. From ElasticSearch documentation, it looks like this is possible but there is no details about how to do it.

Here's what the documentation says:

This must be done at index creation time, or with the update-mapping API before the child type has been created.

There are no details about setting up a parent-child relationship in the update-mapping API documentation.

Intuitively, I think a parent-child relationship should be allowed to be established after a parent already exists since the parent does not need to know anything about the child.

Here's the error I'm getting when I create a new type as a child:

{
"error": {
  "root_cause": [
    {
      "type": "illegal_argument_exception",
      "reason": "can't add a _parent field that points to an already existing type"
    }
  ],
  "type": "illegal_argument_exception",
  "reason": "can't add a _parent field that points to an already existing type"
},
"status": 400
}


问:
Find occurence of a word in a sentence
I want to find the occurence of a certain word in a sentence and then remove it. I'm able to do it but sometimes the word I wanna remove can be a subword. For example I wanna find/remove the word "word" in the sentence "Music is worldwide". My program will fin/remove return a positive value that it found the word "word" in the sentence while in fact it encountered the word "worldwide" and I would like it to return a negative value.
I'm currently using

index = text.find(word)```

Is there any other way to avoid this problem of the word being a subword in a sentence ? Thank you in advance!

答:
I thought of adding a space to the word i.e :

word = " "+ word
index = text.find(word)```

but I wonder if there's a more effective and clean way to do it.

Title: Find occurence of a word in a sentence

Body:
I want to find the occurence of a certain word in a sentence and then remove it. I'm able to do it but sometimes the word I wanna remove can be a subword. For example I wanna find/remove the word "word" in the sentence "Music is worldwide". My program will fin/remove return a positive value that it found the word "word" in the sentence while in fact it encountered the word "worldwide" and I would like it to return a negative value.
I'm currently using

index = text.find(word)

Is there any other way to avoid this problem of the word being a subword in a sentence ? Thank you in advance!

Body:
I thought of adding a space to the word i.e :

word = " "+ word
index = text.find(word)

but I wonder if there's a more effective and clean way to do it.


问:
AVPlayer have still a delay after status reached "ReadyToPlay"
I want to play mp3 files from my Server, i do the following:

```<code>NSURL *url = [NSURL URLWithString:item.audioUrl];

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

self.player = [AVPlayer playerWithPlayerItem:playerItem];

self.player addObserver:self forKeyPath:@"status" options:0 context:nil];

self.hud = [[MBProgressHUD alloc]initWithFrame:CGRectMake(150, 5, 50, 50)];
self.hud.mode = MBProgressHUDModeIndeterminate;
[self.hud show:YES];
[self.containerView addSubview:self.hud];
</code>```

Here is my observeValueForKeyPath:

```<code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

if (object == self.player && [keyPath isEqualToString:@"status"])
{
    if (self.player.status == AVPlayerStatusReadyToPlay)
    {
        [self.hud hide:YES];
        [self.player play];
.
.
.
</code>```

Now the Problem is that even when the Status of the AVPlayer have changed to "readyToPlay" it still takes about 2-3 seconds before it starts playing and of course my loading Spinner gets hidden before the music starts....any Ideas?

答:
```<code>self.player.automaticallyWaitsToMinimizeStalling = NO;
</code>```

Set to NO to play audio immediately after AVPlayerStatusReadyToPlay status!

Body:
I want to play mp3 files from my Server, i do the following:

NSURL *url = [NSURL URLWithString:item.audioUrl];

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

self.player = [AVPlayer playerWithPlayerItem:playerItem];

self.player addObserver:self forKeyPath:@"status" options:0 context:nil];

self.hud = [[MBProgressHUD alloc]initWithFrame:CGRectMake(150, 5, 50, 50)];
self.hud.mode = MBProgressHUDModeIndeterminate;
[self.hud show:YES];
[self.containerView addSubview:self.hud];

Here is my observeValueForKeyPath:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

if (object == self.player && [keyPath isEqualToString:@"status"])
{
    if (self.player.status == AVPlayerStatusReadyToPlay)
    {
        [self.hud hide:YES];
        [self.player play];
.
.
.

Now the Problem is that even when the Status of the AVPlayer have changed to "readyToPlay" it still takes about 2-3 seconds before it starts playing and of course my loading Spinner gets hidden before the music starts....any Ideas?

Body:
self.player.automaticallyWaitsToMinimizeStalling = NO;

Set to NO to play audio immediately after AVPlayerStatusReadyToPlay status!


问:
Fortran 77 conversion to C++
I have a Fortran 77 application that uses Common declarations to "share" memory variables.  Back in the day, when memory was expensive and hard to come by this was the way around it.

The equipment being controlled sets status flags.  These flags reside in these Common variables.

Any suggestions on how to implement the Common functionality in c++?

A class perhaps, with all the common variables being public.  Thus any program instantiating that class will have access to the contents of the Common variables.

Are there any tutorials/guidelines for converting Fortran to C or C++?

Thanks

答: Don't do it at all, common blocks are an anathema in the modern day.</p>

Title: Fortran 77 conversion to C++


问:
Coffee script not working when included in assets
I have some coffee script that switches around some css classes when collapsing a list, however it doesn't seem to work when I put it in a separate .js.coffee file in the /assets/javascripts directory however it does work when I include it in the HAML file. The coffee script seems to compile and is included in head of the page but doesn't work at all. Any ideas?</p>

```<code>  $('#collapseTwo').on 'hidden.bs.collapse', ->
    if $('#collapseOne').hasClass('show')
      $('#collapseOne').addClass('extended')
    $('#collapseOne').removeClass('regular')
    $('#collapseTwo').removeClass('regular')
    $('#collapseTwo').removeClass('extended');

  $('#collapseTwo').on 'show.bs.collapse', ->
    unless $('#collapseOne').hasClass('show')
      $('#collapseTwo').addClass('extended')
    if $('#collapseOne').hasClass('extended')
      $('#collapseOne').removeClass('extended')
      $('#collapseOne').addClass('regular')
      $('#collapseTwo').addClass('regular');

  $('#collapseOne').on 'hidden.bs.collapse', ->
    if $('#collapseTwo').hasClass('show')
      $('#collapseTwo').addClass('extended')
    $('#collapseTwo').removeClass('regular')
    $('#collapseOne').removeClass('regular')
    $('#collapseOne').removeClass('extended');

  $('#collapseOne').on 'show.bs.collapse', ->
    unless $('#collapseTwo').hasClass('show')
      $('#collapseOne').addClass('extended')
    if $('#collapseTwo').hasClass('extended')
      $('#collapseTwo').removeClass('extended')
      $('#collapseOne').addClass('regular')
      $('#collapseTwo').addClass('regular');
</code>```

答:
Add gem 'coffee-rails' to your gemfile, and run bundle install.

And remember to require the coffeescript file in the application.js like //= require moment.

Add $(document).on 'ready page:load', -> as first line in the coffee file.

Body:
I have some coffee script that switches around some css classes when collapsing a list, however it doesn't seem to work when I put it in a separate .js.coffee file in the /assets/javascripts directory however it does work when I include it in the HAML file. The coffee script seems to compile and is included in head of the page but doesn't work at all. Any ideas?

  $('#collapseTwo').on 'hidden.bs.collapse', ->
    if $('#collapseOne').hasClass('show')
      $('#collapseOne').addClass('extended')
    $('#collapseOne').removeClass('regular')
    $('#collapseTwo').removeClass('regular')
    $('#collapseTwo').removeClass('extended');

  $('#collapseTwo').on 'show.bs.collapse', ->
    unless $('#collapseOne').hasClass('show')
      $('#collapseTwo').addClass('extended')
    if $('#collapseOne').hasClass('extended')
      $('#collapseOne').removeClass('extended')
      $('#collapseOne').addClass('regular')
      $('#collapseTwo').addClass('regular');

  $('#collapseOne').on 'hidden.bs.collapse', ->
    if $('#collapseTwo').hasClass('show')
      $('#collapseTwo').addClass('extended')
    $('#collapseTwo').removeClass('regular')
    $('#collapseOne').removeClass('regular')
    $('#collapseOne').removeClass('extended');

  $('#collapseOne').on 'show.bs.collapse', ->
    unless $('#collapseTwo').hasClass('show')
      $('#collapseOne').addClass('extended')
    if $('#collapseTwo').hasClass('extended')
      $('#collapseTwo').removeClass('extended')
      $('#collapseOne').addClass('regular')
      $('#collapseTwo').addClass('regular');


问:
javassist copy a method with annotation
This is the original method:

```<code>  @GET
  @Produces({"application/json"})
  public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui)
  {
    return null
  }
</code>```

I want to copy this method but add a new String parameter,and the annotations of the new method is the same as before,like this:

```<code>  @GET
  @Produces({"application/json"})
  public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui,String newParam)
  {
    return null
  }
</code>```

I use javassist to do it,i don`t want to add a "get" annotation and then add a "produces" annotation,because there may be many other annotations which are unkown.How to do it as a common way?

答:
When You try adding a new parameter to a method , Javassist does not allow to add an extra parameter to an existing method,Instead of doing that, a new method receiving the extra parameter as well as the other parameters is added to the same class.

A copy of the the CtMethod object can be obtained by CtNewMethod.copy().

Try this to create a copy of Your previous method. And can you explain exactly what you want to be done with annotations?

Title: javassist copy a method with annotation

Body:
This is the original method:

  @GET
  @Produces({"application/json"})
  public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui)
  {
    return null
  }

I want to copy this method but add a new String parameter,and the annotations of the new method is the same as before,like this:

  @GET
  @Produces({"application/json"})
  public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui,String newParam)
  {
    return null
  }

I use javassist to do it,i don`t want to add a "get" annotation and then add a "produces" annotation,because there may be many other annotations which are unkown.How to do it as a common way?


问:
Parameterize Azure subscription in Vsts build task
I have some build tasks that should be ran against resources located in different Azure subscription. In order to have only one build definition to maintain, i need to be able to parameterize the Azure Subscription field.

For the moment, i have to duplicate the original build definition and only change the subscription in each one, that is painful ti maintain.

The sample below does not work. I tried with the subscription ID, the subscription name, connected service name...

How can i do that ?

答:
You can’t parameterize Azure subscription field in build or release.

There is a similar user voice that you can vote and follow up: Allow service connections to be parameterized in task groups


问:
Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
I have an application with three tabs.

Each tab has its own layout .xml file. The main.xml has its own map fragment. It's the one that shows up when the application first launches.

Everything works fine except for when I change between tabs. If I try to switch back to the map fragment tab, I get this error. Switching to and between other tabs works just fine.

What could be wrong here?

This is my main class and my main.xml, as well as a relevant class that I use ( you will also find the error log at the bottom )

main class

```<code>package com.nfc.demo;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;

public class NFCDemoActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        bar.addTab(bar
                .newTab()
                .setText("Map")
                .setTabListener(
                        new TabListener<MapFragment>(this, "map",
                                MapFragment.class)));
        bar.addTab(bar
                .newTab()
                .setText("Settings")
                .setTabListener(
                        new TabListener<SettingsFragment>(this, "settings",
                                SettingsFragment.class)));
        bar.addTab(bar
                .newTab()
                .setText("About")
                .setTabListener(
                        new TabListener<AboutFragment>(this, "about",
                                AboutFragment.class)));

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
        // setContentView(R.layout.main);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    public static class TabListener<T extends Fragment> implements
            ActionBar.TabListener {
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private final Bundle mArgs;
        private Fragment mFragment;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            this(activity, tag, clz, null);
        }

        public TabListener(Activity activity, String tag, Class<T> clz,
                Bundle args) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            mArgs = args;

            // Check to see if we already have a fragment for this tab,
            // probably from a previously saved state. If so, deactivate
            // it, because our initial state is that a tab isn't shown.
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) {
                FragmentTransaction ft = mActivity.getFragmentManager()
                        .beginTransaction();
                ft.detach(mFragment);
                ft.commit();
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(),
                        mArgs);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT)
                         .show();
        }
    }

}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</code>```

relevant class ( MapFragment.java )

```<code>package com.nfc.demo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MapFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.main, container, false);
    }

    public void onDestroy() {
        super.onDestroy();
    }
}
</code>```

error

```<code>android.view.InflateException: Binary XML file line #7:
     Error inflating class fragment
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
   at com.nfc.demo.MapFragment.onCreateView(MapFragment.java:15)
   at android.app.Fragment.performCreateView(Fragment.java:1695)
   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
   at android.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1255)
   at android.app.BackStackRecord.run(BackStackRecord.java:672)
   at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
   at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
   at android.os.Handler.handleCallback(Handler.java:725)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5039)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
   at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.IllegalArgumentException:
     Binary XML file line #7: Duplicate id 0x7f040005, tag null, or
     parent id 0xffffffff with another fragment for
     com.google.android.gms.maps.MapFragment
   at android.app.Activity.onCreateView(Activity.java:4722)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
   ... 19 more
</code>```

答:
I respect all the answers but i found this one liner solution:
If n Is the Number of tabs then:

```<code> mViewPager.setOffscreenPageLimit(n);
</code>```

Example:
In case mentioned :

```<code> mViewPager.setOffscreenPageLimit(2);
</code>```

View pager implements a queue so, you don't have to let it remove that fragment. onCreateView is called only once.

Body:
I have an application with three tabs.

Each tab has its own layout .xml file. The main.xml has its own map fragment. It's the one that shows up when the application first launches.

Everything works fine except for when I change between tabs. If I try to switch back to the map fragment tab, I get this error. Switching to and between other tabs works just fine.

What could be wrong here?

This is my main class and my main.xml, as well as a relevant class that I use ( you will also find the error log at the bottom )

main class

package com.nfc.demo;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;

public class NFCDemoActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        bar.addTab(bar
                .newTab()
                .setText("Map")
                .setTabListener(
                        new TabListener<MapFragment>(this, "map",
                                MapFragment.class)));
        bar.addTab(bar
                .newTab()
                .setText("Settings")
                .setTabListener(
                        new TabListener<SettingsFragment>(this, "settings",
                                SettingsFragment.class)));
        bar.addTab(bar
                .newTab()
                .setText("About")
                .setTabListener(
                        new TabListener<AboutFragment>(this, "about",
                                AboutFragment.class)));

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
        // setContentView(R.layout.main);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    public static class TabListener<T extends Fragment> implements
            ActionBar.TabListener {
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private final Bundle mArgs;
        private Fragment mFragment;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            this(activity, tag, clz, null);
        }

        public TabListener(Activity activity, String tag, Class<T> clz,
                Bundle args) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            mArgs = args;

            // Check to see if we already have a fragment for this tab,
            // probably from a previously saved state. If so, deactivate
            // it, because our initial state is that a tab isn't shown.
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) {
                FragmentTransaction ft = mActivity.getFragmentManager()
                        .beginTransaction();
                ft.detach(mFragment);
                ft.commit();
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(),
                        mArgs);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT)
                         .show();
        }
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

relevant class ( MapFragment.java )

package com.nfc.demo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MapFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.main, container, false);
    }

    public void onDestroy() {
        super.onDestroy();
    }
}

error

android.view.InflateException: Binary XML file line #7:
     Error inflating class fragment
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
   at com.nfc.demo.MapFragment.onCreateView(MapFragment.java:15)
   at android.app.Fragment.performCreateView(Fragment.java:1695)
   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
   at android.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1255)
   at android.app.BackStackRecord.run(BackStackRecord.java:672)
   at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
   at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
   at android.os.Handler.handleCallback(Handler.java:725)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5039)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
   at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.IllegalArgumentException:
     Binary XML file line #7: Duplicate id 0x7f040005, tag null, or
     parent id 0xffffffff with another fragment for
     com.google.android.gms.maps.MapFragment
   at android.app.Activity.onCreateView(Activity.java:4722)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
   ... 19 more

Body:
I respect all the answers but i found this one liner solution:
If n Is the Number of tabs then:

 mViewPager.setOffscreenPageLimit(n);

Example:
In case mentioned :

 mViewPager.setOffscreenPageLimit(2);

View pager implements a queue so, you don't have to let it remove that fragment. onCreateView is called only once.


问:
Why won't this JAVA code work as expected?
So, this seems fairly simple bit of code.But when I run this, it gives me strange output.
First, I store the number of elements of queries[] Array in NumQ variable.Then, I store the values of elements by looping from 0 to numQ-1.It works in any other case.

```<code>int numQ=sc.nextInt();
  String queries[]=new String[numQ];
    for(int i=0;i<numQ;i++){

        queries[i]=sc.nextLine();
    }
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);
</code>```

In my case, inputs are-(note that it even doesn't ask for the value at index 2.numQ is 3)

And here is the output.

See, at queries[0], it stores blank value(blue selection is blank).At queries[ 1 ], it stores the first input(which was to be stored at index 0.And it stores the index 1 value at index 2 and so on.)

So what's the problem with my code.
Thanks in advance:-)

答:
I suppose sc is a Scanner Object. The method nextInt() scan only int part before newline. So you have to use sc.nextLine() to skip the newline

```<code>int numQ=sc.nextInt();
sc.nextLine();

String queries[]=new String[numQ];
for(int i=0;i<numQ;i++){
    queries[i]=sc.nextLine();
}
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);
</code>```

Body:
So, this seems fairly simple bit of code.But when I run this, it gives me strange output.
First, I store the number of elements of queries[] Array in NumQ variable.Then, I store the values of elements by looping from 0 to numQ-1.It works in any other case.

int numQ=sc.nextInt();
  String queries[]=new String[numQ];
    for(int i=0;i<numQ;i++){

        queries[i]=sc.nextLine();
    }
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);

In my case, inputs are-(note that it even doesn't ask for the value at index 2.numQ is 3)

And here is the output.

See, at queries[0], it stores blank value(blue selection is blank).At queries[ 1 ], it stores the first input(which was to be stored at index 0.And it stores the index 1 value at index 2 and so on.)

So what's the problem with my code.
Thanks in advance:-)

Body:
I suppose sc is a Scanner Object. The method nextInt() scan only int part before newline. So you have to use sc.nextLine() to skip the newline

int numQ=sc.nextInt();
sc.nextLine();

String queries[]=new String[numQ];
for(int i=0;i<numQ;i++){
    queries[i]=sc.nextLine();
}
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);


问:
Delete all lines until a specific line in Notepad++
I have to edit a lot of source codes similar to each other.

```<code>random blah
 random blah
blah
<table style="width: 232px; font-size: small;" cellpadding="0" cellspacing="0">....
</code>```

What I want to do is to delete lines until table tag. I think I can do it with Regex search but I couldnt write the regex pattern.
Thank you

答:
you can try something like:

```<code>(^.*$\n)*<table(.+)>
</code>```

First group will match all lines before your table tag %)

Body:
I have to edit a lot of source codes similar to each other.

random blah
 random blah
blah

....

What I want to do is to delete lines until table tag. I think I can do it with Regex search but I couldnt write the regex pattern.
Thank you

Body:
you can try something like:

(^.*$\n)*<table(.+)>

First group will match all lines before your table tag %)