问:
JDBC: complains about invalid sign but seems fine
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

```<code>Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }
</code>```

答:
As I put in a comment above, the issue could be due to the extra Semicolon at the end of your SQL statement. see this article

You may also want to look at PreparedStatments to make your life easier. Here would be a rough translation of your above code. I have left some parts, and there are most likely errors.

```<code>String query = "insert into user(user_id, username, age, creation_ts) values(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(query);
... //fill in all your parameters
pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()) );
... //execute here
</code>```

Body:
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }

Body:
As I put in a comment above, the issue could be due to the extra Semicolon at the end of your SQL statement. see this article

You may also want to look at PreparedStatments to make your life easier. Here would be a rough translation of your above code. I have left some parts, and there are most likely errors.

String query = "insert into user(user_id, username, age, creation_ts) values(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(query);
... //fill in all your parameters
pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()) );
... //execute here


来源: stackexchange

问:
How to chop ruby string having a random number
My string is - main_string = 'FA117RWD-20 ABC Program (version 10.0)'

In this string I just want to read FA117RWD-20 and in this string version is random which will be coming from somewhere, its version 10 right now it can be version 20 at some other time also the part that I want to read i.e. FA117RWD-20 will also be coming from somewhere randomly so is not of fix length, basically I want to chop everything that is coming after this string. How should I do it?

Thanks

答:
you can just use #split

```<code>'FA117RWD-20 ABC Program (version 10.0)'.split(' ').first
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can just use #split

'FA117RWD-20 ABC Program (version 10.0)'.split(' ').first


问:
PHP PDO MySQL strings and variables
Why does this work when using the value direct?

```<code>$stmt = $db->prepare('SELECT tablename FROM database WHERE item = :item');
$stmt->execute(array('item ' => "somevalue" ));
$result = $stmt->fetchAll();
</code>```

But this one does not work when using a variable?

```<code>$itemstring = "somevalue"
$stmt = $db->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array('item ' => $itemstring));
$result = $stmt->fetchAll();
</code>```

Am I missing something obvious?

This is on WAMP 2.4/MySQL

Only change is that I am using a variable instead of a string?

答:
```<code>This is late but I'm pretty sure the syntax should be like the below. And this can help you understand a bit more about how PDO works.
</code>```

https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

```<code>$itemstring = "somevalue";
$stmt = $dbcon->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array(':item' => $itemstring));<-- Colon in the identifier
$result = $stmt->fetchAll();
</code>```

Or

```<code>$itemstring = "somevalue";
$query="SELECT tablename FROM catalogs WHERE item = :item";
$stmt = $dbcon->prepare($query);
$params = array(':item' => $itemstring);<-- Colon in the identifier, setting parameters.
$stmt->execute($params);
$result = $stmt->fetchAll();
</code>```

Title: PHP PDO MySQL strings and variables

Body:
Why does this work when using the value direct?

$stmt = $db->prepare('SELECT tablename FROM database WHERE item = :item');
$stmt->execute(array('item ' => "somevalue" ));
$result = $stmt->fetchAll();

But this one does not work when using a variable?

$itemstring = "somevalue"
$stmt = $db->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array('item ' => $itemstring));
$result = $stmt->fetchAll();

Am I missing something obvious?

This is on WAMP 2.4/MySQL

Only change is that I am using a variable instead of a string?

Body:
This is late but I'm pretty sure the syntax should be like the below. And this can help you understand a bit more about how PDO works.

https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

$itemstring = "somevalue";
$stmt = $dbcon->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array(':item' => $itemstring));<-- Colon in the identifier
$result = $stmt->fetchAll();

Or

$itemstring = "somevalue";
$query="SELECT tablename FROM catalogs WHERE item = :item";
$stmt = $dbcon->prepare($query);
$params = array(':item' => $itemstring);<-- Colon in the identifier, setting parameters.
$stmt->execute($params);
$result = $stmt->fetchAll();


问:
What is the difference between Php $this->$propery_name and $this->propery_name
```<code>    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }
</code>```

I am following a tutorial on object-oriented programming, however, the instructor came up with a new code structure that I have not seen before without a clear explanation of why he did so. if you notice within the if(statement) the
$this->$protected_property_name statement has two $ signs one for the $this and the other for the  $protected_property_name normally it should only be
$this->protected_property_name without having a dollar sign on the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was triggered. the complete code looks like this

```<code>class Addrress{

  protected $_postal_code;

  function __get($name){
    if(!$this->_postal_code){
        $this->_postal_code = $this->_postal_code_guess();
    }

    //Attempt to return protected property by name

    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

    //Unable to access property; trigger error.
    trigger_error('Undefined property via __get:() '. $name);
    return NULL;
}
}
</code>```

答:
Let us assume that we have a class

```<code>class Test {
   public $myAttr = 1;
}
var $x = new Test();
</code>```

We can access the public attribute like $x->myAttr.

What if we have the name of the attribute in a variable, like

```<code>$var = 'myAttr';
</code>```

We can access the value of the attribute with $x->$var

Body:
    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

I am following a tutorial on object-oriented programming, however, the instructor came up with a new code structure that I have not seen before without a clear explanation of why he did so. if you notice within the if(statement) the
$this->$protected_property_name statement has two $ signs one for the $this and the other for the  $protected_property_name normally it should only be
$this->protected_property_name without having a dollar sign on the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was triggered. the complete code looks like this

class Addrress{

  protected $_postal_code;

  function __get($name){
    if(!$this->_postal_code){
        $this->_postal_code = $this->_postal_code_guess();
    }

    //Attempt to return protected property by name

    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

    //Unable to access property; trigger error.
    trigger_error('Undefined property via __get:() '. $name);
    return NULL;
}
}

Body:
Let us assume that we have a class

class Test {
   public $myAttr = 1;
}
var $x = new Test();

We can access the public attribute like $x->myAttr.

What if we have the name of the attribute in a variable, like

$var = 'myAttr';

We can access the value of the attribute with $x->$var


问:
datatable does not support if more than 60000 records are being fetched
we want to store large number of data (more than 60K rows ) in datatable but the datatable fails to executes and output is not coming well. The datatable will not fails till 20000 records. Here is fhe following source code

```<code> <div class="row">
                        <table id="customer_table"  class="display" cellspacing="0" width="100%">
                         <thead>
                    <tr>
                        <th>#</th>
                        <th>Customer Name</th>
                        <th>Email</th>
                        <th>Group</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>

    <?php   for($p=1;$p<=200;$p++)

    {

    $ch = curl_init("https://$shop_name/admin/customers.json?limit=250&page=".$p."");
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json",
                                        "X-Shopify-Access-Token: $store_token"));
                     $result = curl_exec($ch);
                    $decoded_customer = json_decode($result, true);
                    //var_dump($decoded_customer);
                    ?>

    <?php for($i=0;$i<count($decoded_customer['customers']);$i++)

    {
    ?>
            <tr>
            <input type="hidden" value="<?php echo $decoded_customer['customers'][$i]['id']; ?>" >
            <td>#</td>
            <td><?php echo $decoded_customer['customers'][$i]['first_name']." ".$decoded_customer['customers'][$i]['last_name'];?></td>
            <td><?php echo $decoded_customer['customers'][$i]['email']; ?></td>
            <td>

      <select class="form-control" >
           <option value="" >
               No Selected
            </option>
                <?php
                session_start();

                $shop_name = $_SESSION['shop'];
                include("dbconnect.php");

                $sql_select_tbl_shop = "SELECT * FROM `store_info_tbl` WHERE `store_name` = '$shop_name'";
                $select_tbl_shop = mysql_query($sql_select_tbl_shop);

                if(mysql_num_rows($select_tbl_shop)>0){

                $row_select_val=mysql_fetch_array($select_tbl_shop );
                $shop_id=$row_select_val['id'];

                //select selected group name
                $customer_id=$decoded_customer['customers'][$i]['id'];

                $sqlselectgroup_customer="SELECT * FROM `tbl_group` WHERE `store_name`='$shop_id'";
                $resselectgroup_customer=mysql_query($sqlselectgroup_customer);
                if(mysql_num_rows($resselectgroup_customer))
                {
                  while($rowselectgroup_customer=mysql_fetch_assoc($resselectgroup_customer))
                  {
                $sqlselectcustomergroup="SELECT * FROM `tbl_customer_detail` WHERE `customer_shop_id`='$customer_id'";
                $resselectcustomergroup=mysql_query($sqlselectcustomergroup);

                if(mysql_num_rows($resselectcustomergroup)>0){
                //$rowselectcustomer=mysql_num_rows($resselectcustomergroup);

                 //$rowid=mysql_fetch_array('group_name');
                 $rowid=mysql_fetch_array($resselectcustomergroup);
                 $customer_group=$rowid['group_name'];

                ?>

            <option value="<?php echo $rowselectgroup_customer['id']; ?>" <?php if($customer_group==$rowselectgroup_customer['id']) { ?>selected <?php } ?> >
            <?php echo $rowselectgroup_customer['group_name']; ?>
            </option>
              <?php } else{ ?>

           <option value="<?php echo $rowselectgroup_customer['id']; ?>" >
            <?php echo $rowselectgroup_customer['group_name']; ?>
            </option>

                <?php  } } } } ?>

            </select>
            </td>
            <td><button type="button" class="btn btn-primary save">Save</button></td>
            </tr>
            <?php } } ?>

    </tbody>

    </table>

    <script type="text/javascript" >
               $(document).ready(function(){
                 $('#customer_table').DataTable();

               });
               $(document).on('click','.save',function(){
                   var shopify_customer_id=$(this).parent().parent().find('input').val();
                   var customer_name=$(this).parent().parent().find('td').eq(1).html();
                   var customer_email=$(this).parent().parent().find('td').eq(2).html();
                   var group_name=$(this).parent().parent().find('td').find('select').val();
                  //alert(shopify_customer_id+customer_name+customer_email+group_name);

                  $.ajax({
                        type: "post",
                        url: "ajaxcustomerdata.php",
                        data: {
                            shopify_customer_id:shopify_customer_id,
                            customer_name:customer_name,
                            customer_email:customer_email,
                            group_name:group_name
                        },
                        success: function (data){
                           alert(data);

                        },
                        error: function (xhr, ajaxOptions, thrownError){
                        }
                    });

                   });

            </script>
            <script>

            </script>

    </div>
</code>```

If any one has any kind of suggestion please help me out to resolve this problem

答:
Please read https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html official post from data table. it is showing how to add thousands of record added in data table.

Below is example of this.

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        serverSide: true,
        ordering: false,
        searching: false,
        ajax: function ( data, callback, settings ) {
            var out = [];

            for ( var i=data.start, ien=data.start+data.length ; i<ien ; i++ ) {
                out.push( [ i+'-1', i+'-2', i+'-3', i+'-4', i+'-5' ] );
            }

            setTimeout( function () {
                callback( {
                    draw: data.draw,
                    data: out,
                    recordsTotal: 160421,
                    recordsFiltered: 160421
                } );
            }, 50 );
        },
        scrollY: 600,
        scroller: {
            loadingIndicator: true
        }
    } );
} );
</code>```

html for datatable :

```<code><table id="example" class="display nowrap" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>First name</th>
                <th>Last name</th>
                <th>ZIP / Post code</th>
                <th>Country</th>
            </tr>
        </thead>
    </table>
</code>```

Body:
we want to store large number of data (more than 60K rows ) in datatable but the datatable fails to executes and output is not coming well. The datatable will not fails till 20000 records. Here is fhe following source code

                        #
                        Customer Name
                        Email
                        Group
                        Action

    <?php   for($p=1;$p<=200;$p++)

    {

    $ch = curl_init("https://$shop_name/admin/customers.json?limit=250&page=".$p."");
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json",
                                        "X-Shopify-Access-Token: $store_token"));
                     $result = curl_exec($ch);
                    $decoded_customer = json_decode($result, true);
                    //var_dump($decoded_customer);
                    ?>

    <?php for($i=0;$i<count($decoded_customer['customers']);$i++)

    {
    ?>

            <input type="hidden" value="<?php echo $decoded_customer['customers'][$i]['id']; ?>" >
            #
            <?php echo $decoded_customer['customers'][$i]['first_name']." ".$decoded_customer['customers'][$i]['last_name'];?>
            <?php echo $decoded_customer['customers'][$i]['email']; ?>

      <select class="form-control" >
           <option value="" >
               No Selected
            </option>
                <?php
                session_start();

                $shop_name = $_SESSION['shop'];
                include("dbconnect.php");

                $sql_select_tbl_shop = "SELECT * FROM `store_info_tbl` WHERE `store_name` = '$shop_name'";
                $select_tbl_shop = mysql_query($sql_select_tbl_shop);

                if(mysql_num_rows($select_tbl_shop)>0){

                $row_select_val=mysql_fetch_array($select_tbl_shop );
                $shop_id=$row_select_val['id'];

                //select selected group name
                $customer_id=$decoded_customer['customers'][$i]['id'];

                $sqlselectgroup_customer="SELECT * FROM `tbl_group` WHERE `store_name`='$shop_id'";
                $resselectgroup_customer=mysql_query($sqlselectgroup_customer);
                if(mysql_num_rows($resselectgroup_customer))
                {
                  while($rowselectgroup_customer=mysql_fetch_assoc($resselectgroup_customer))
                  {
                $sqlselectcustomergroup="SELECT * FROM `tbl_customer_detail` WHERE `customer_shop_id`='$customer_id'";
                $resselectcustomergroup=mysql_query($sqlselectcustomergroup);

                if(mysql_num_rows($resselectcustomergroup)>0){
                //$rowselectcustomer=mysql_num_rows($resselectcustomergroup);

                 //$rowid=mysql_fetch_array('group_name');
                 $rowid=mysql_fetch_array($resselectcustomergroup);
                 $customer_group=$rowid['group_name'];

                ?>

            <option value="<?php echo $rowselectgroup_customer['id']; ?>" <?php if($customer_group==$rowselectgroup_customer['id']) { ?>selected <?php } ?> >
            <?php echo $rowselectgroup_customer['group_name']; ?>
            </option>
              <?php } else{ ?>

           <option value="<?php echo $rowselectgroup_customer['id']; ?>" >
            <?php echo $rowselectgroup_customer['group_name']; ?>
            </option>

                <?php  } } } } ?>

            </select>

            <button type="button" class="btn btn-primary save">Save</button>

            <?php } } ?>

If any one has any kind of suggestion please help me out to resolve this problem

Body:
Please read https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html official post from data table. it is showing how to add thousands of record added in data table.

Below is example of this.

$(document).ready(function() {
    $('#example').DataTable( {
        serverSide: true,
        ordering: false,
        searching: false,
        ajax: function ( data, callback, settings ) {
            var out = [];

            for ( var i=data.start, ien=data.start+data.length ; i<ien ; i++ ) {
                out.push( [ i+'-1', i+'-2', i+'-3', i+'-4', i+'-5' ] );
            }

            setTimeout( function () {
                callback( {
                    draw: data.draw,
                    data: out,
                    recordsTotal: 160421,
                    recordsFiltered: 160421
                } );
            }, 50 );
        },
        scrollY: 600,
        scroller: {
            loadingIndicator: true
        }
    } );
} );

html for datatable :

<table id="example" class="display nowrap" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>First name</th>
                <th>Last name</th>
                <th>ZIP / Post code</th>
                <th>Country</th>
            </tr>
        </thead>
    </table>


问:
Account Locked in API Manager Store & Publisher 2.1.0
Is there a way to lock a user's account after a certain number of failed login attempts to the API Store and API Publisher? I already check at FAQ API Manager, but then the documentation redirect to Identity Server files.

Its there any method on how to solve this issues?

Thank You.

答:
You can change the following properties in APIM_HOME/repository/conf/identity/identity-mgt.properties file.

Authentication.Policy.Account.Lock.On.Failure.Max.Attempts

```<code>Authentication.Policy.Password.Expire.Time=0
# If account verification is not enabled, following property will decide where user must be lock or not after user is created
Authentication.Policy.Account.Lock.On.Creation=false
Authentication.Policy.Account.Lock.Time=0
Authentication.Policy.Account.Lock.On.Failure=false
Authentication.Policy.Account.Lock.On.Failure.Max.Attempts=0
</code>```

Body:
You can change the following properties in APIM_HOME/repository/conf/identity/identity-mgt.properties file.

Authentication.Policy.Account.Lock.On.Failure.Max.Attempts

Authentication.Policy.Password.Expire.Time=0
# If account verification is not enabled, following property will decide where user must be lock or not after user is created
Authentication.Policy.Account.Lock.On.Creation=false
Authentication.Policy.Account.Lock.Time=0
Authentication.Policy.Account.Lock.On.Failure=false
Authentication.Policy.Account.Lock.On.Failure.Max.Attempts=0


问:
Hiding code when php field doesn't have value
I need to hide the code if a PHP field value is empty.

Here's the code:

```<code><?php if( get_field('volunteer_causes') ): ?>
                <div class="program-single-volunteer-causes">
                    <h4>Volunteer Causes</h4>
                    <?php
                    $terms = get_field('volunteer_causes');

                    if( $terms ): ?>

                        <ul>

                        <?php foreach( $terms as $term ): ?>

                            <li>
                                <span><?php echo $term ?></span>
                            </li>

                        <?php endforeach; ?>

                        </ul>

                    <?php endif; ?>
                </div><!--program-single-volunteer-causes-->
</code>```

As it is, if there's no value in the 'volunteer_causes' field then the HTML will remain.

I've tried using echo for each line containing the HTML.

Example: <?php echo '
Volunteer Causes
'; ?>

However, this changed nothing.

This method works to remove all code when there's no value present in the field:

 <?php if( !empty(the_field('volunteer_causes')) ): ?>

... however, my HTML is missing when the values do show up.

答:
I ended up paying someone $5 on a freelancer site to get it to work. This is what they came up with and it works!      </p>

```<code><?php
$volunteer_causes = get_field('volunteer_causes');
if($volunteer_causes[0]){ ?>
<div class="program-single-volunteer-causes">
<h4>Volunteer Causes</h4>
<?php
$terms = get_field('volunteer_causes');

if( $terms ): ?>

<ul>

<?php foreach( $terms as $term ): ?>

<li>
<span><?php echo $term ?></span>
</li>

<?php endforeach; ?>

</ul>

<?php endif;
}
?>
</div>
</code>```

Body:
I need to hide the code if a PHP field value is empty.

Here's the code:

<?php if( get_field('volunteer_causes') ): ?>

Volunteer Causes

                    <?php
                    $terms = get_field('volunteer_causes');

                    if( $terms ): ?>

                        <?php foreach( $terms as $term ): ?>

                                <?php echo $term ?>

                        <?php endforeach; ?>

                    <?php endif; ?>

As it is, if there's no value in the 'volunteer_causes' field then the HTML will remain.

I've tried using echo for each line containing the HTML.

Example: <?php echo '
Volunteer Causes
'; ?>

However, this changed nothing.

This method works to remove all code when there's no value present in the field:

 <?php if( !empty(the_field('volunteer_causes')) ): ?>

... however, my HTML is missing when the values do show up.

Body:
I ended up paying someone $5 on a freelancer site to get it to work. This is what they came up with and it works!

<?php
$volunteer_causes = get_field('volunteer_causes');
if($volunteer_causes[0]){ ?>
<div class="program-single-volunteer-causes">
<h4>Volunteer Causes</h4>
<?php
$terms = get_field('volunteer_causes');

if( $terms ): ?>

<ul>

<?php foreach( $terms as $term ): ?>

<li>
<span><?php echo $term ?></span>
</li>

<?php endforeach; ?>

</ul>

<?php endif;
}
?>
</div>


问:
Programatic Access to Company Shared Outlook Contacts in Web App
I have created a public folder mailbox and a root public folder for our organization in Office 365.  I've also created a Shared Contacts folder in Outlook and added a couple of contacts.

Now I want to be able to programatically access these shared contacts (list, view, add, remove) in our web application, an SPA written in Angular4.

We are already authenticating against Azure AD, and we are already pulling information from MS Graph.  However I don't see any way to access public folders in Graph.

How can I access these shared contacts in our web app?  I'm open to using something other than MS Graph, if there is another REST API that does what I need.

答:
As far as I know, public folder access is still not available through the Graph API (or any other REST API).

You need to use Exchange Web Services (EWS).
Public folder access with EWS is described at https://msdn.microsoft.com/library/office/jj945067(v=exchg.150).aspx.


问:
Windows server 2012 URI showing undefined in a file path in IE
I have a software package which has following components.

AngularJS client end

Windows service on the server end.

There is a functionality I have - When client requests for a report, I generate it on the server side and save it at a path.
Path where the file is saved is returned to the client.

Issue here is if i am returning /reportfolder/filename from server then on the client side it is becoming /reportfolder/undefined/filename.

This is just happening in Windows Server 2012 r2 in IE browser.
When I tested the same in Windows 7 IE browser, no such issue happens.

Please suggest.

答:
I debugged the code and found that i was using

window.location.origin
  in java script file to generate the complete report path.
  IE 11 does not support window.location.origin in Windows Server 2012. Hence it was returning undefined.

Thanks!


问:
Android: Order ID of the purchased app
We are planning to move from a paid app to a free one with in app purchase. We need to give any user, who paid for the app, get the in app purchase for free.

I am thinking of the following solution. We will store user's unique ID (or unique Order ID) inside our servers. When we release a new, free version of the app, we can check the unique user ID (or Order ID) against our server. If there is a match, we give them the in app purchase for free.

The question is:

If we get the user's email, that would be too sensitive, and user may
not be willing to give it.

Can we get the order ID of the app, and check it against our Google
Play list of order IDs?

Any other unique IDs of the user that we can use to verify that they
have bought the app before?

答:
Getting email address will need you to modify your existing Paid app. Also it's not recommended for above approach ( + cases where users have multiple accounts in same phone and doesn't remember which email is used will create more issues)

I would recommend to use https://developer.android.com/guide/topics/manifest/manifest-element.html#uid

android:sharedUserId

The name of a Linux user ID that will be shared with other
  applications. By default, Android assigns each application its own
  unique user ID. However, if this attribute is set to the same value
  for two or more applications, they will all share the same ID —
  provided that they are also signed by the same certificate.
  Application with the same user ID can access each other's data and, if
  desired, run in the same process.

Define same userId across paid app and new FREE app with in-app purchases. Certain data within paid app can be used to identify the user without asking any more input from users.

Take a look at one of solution provided in this answer by user caw Offering additional media resources (graphics/sounds) as Google Play in-app billed items

Title: Android: Order ID of the purchased app


问:
unable to understand ruby method call
I have a method definition in ruby file (get_java_opts)-
Then one more method calls this "get_java_opts" method with below syntax-
What is this line doing?-

```<code>get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts
</code>```

Code from my ruby file-

```<code>def start
  appdir = "#{@rootdir}/mydir"
  wo_prop = "#{@rootdir}/app.properties"
  get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts
</code>```

Method definition-

```<code>def get_java_opts
  yml = "#{@rootdir}/#{@test}.yaml"
  y = YAML.load_file(yml) if File.exists?(yml)
  java_opts = y[@app]['java_opts'] rescue "No YAML found"
end
</code>```

答:
It is called "ternary operator". This line

```<code>get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts
</code>```

is equivalent to this

```<code>if get_java_opts
  my_java_opts = get_java_opts
else
  my_java_opts = @java_opts
end
</code>```

Title: unable to understand ruby method call

Body:
I have a method definition in ruby file (get_java_opts)-
Then one more method calls this "get_java_opts" method with below syntax-
What is this line doing?-

get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts

Code from my ruby file-

def start
  appdir = "#{@rootdir}/mydir"
  wo_prop = "#{@rootdir}/app.properties"
  get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts

Method definition-

def get_java_opts
  yml = "#{@rootdir}/#{@test}.yaml"
  y = YAML.load_file(yml) if File.exists?(yml)
  java_opts = y[@app]['java_opts'] rescue "No YAML found"
end

Body:
It is called "ternary operator". This line

get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts

is equivalent to this

if get_java_opts
  my_java_opts = get_java_opts
else
  my_java_opts = @java_opts
end


问:
When using object destructuring assignment, why is a property "name" cast to string?
Given

let obj = {name: 1};
console.log(typeof obj.name, obj.name); // `"number"`, `1````
</div>
</div>
</p>

<p>Why is <code>name</code> identifier cast to string when using <code>var</code> at object destructuring assignment?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {name: 1};
var {name} = obj;
console.log(name, typeof name); // `1` `string`</code>```

But not using let or const?

let obj = {name: 1};
let {name} = obj;
console.log(name, typeof name);```
</div>
</div>
</p>

<p>We can avoid this unexpected result by defining a different identifier</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {name: 1};
var {name:_name} = obj;
console.log(_name, typeof _name);</code>```

though curious as to the significance of var returning different results than let or const for the name identifier at a browser environment?

答:
This behaviour is defined by the scope in which the code is being executed.

name refers to window.name property, which descriptor has a setter to convert it to string when being assigned as window.name = 1:

A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)

When being executed in global scope, var name = ... assigns a value to window.name. While let and const declare block-scoped variables.

When being executed in local scope, name will refer to local variable in both cases:

```<code>(() => {
 var obj = {name: 1};
 var {name} = obj;
 console.log(typeof name); // 'number'
})();
</code>```

Body:
Given

let obj = {name: 1};
console.log(typeof obj.name, obj.name); // `"number"`, `1`

Why is name identifier cast to string when using var at object destructuring assignment?

let obj = {name: 1};
var {name} = obj;
console.log(name, typeof name); // `1` `string`

But not using let or const?

let obj = {name: 1};
let {name} = obj;
console.log(name, typeof name);

We can avoid this unexpected result by defining a different identifier

let obj = {name: 1};
var {name:_name} = obj;
console.log(_name, typeof _name);

though curious as to the significance of var returning different results than let or const for the name identifier at a browser environment?

Body:
This behaviour is defined by the scope in which the code is being executed.

name refers to window.name property, which descriptor has a setter to convert it to string when being assigned as window.name = 1:

A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)

When being executed in global scope, var name = ... assigns a value to window.name. While let and const declare block-scoped variables.

When being executed in local scope, name will refer to local variable in both cases:

(() => {
 var obj = {name: 1};
 var {name} = obj;
 console.log(typeof name); // 'number'
})();


问:
Rails 3 Routing Resources with Variable Namespace
Is it possible to have a variable namespace? I have restful resources like the following:

```<code>resources :articles
resources :persons
</code>```

But I need to scope these inside a variable namespace, such that it responds to URLs of the form:

```<code>':edition/:controller/:action/:id'
</code>```

for example:

/foobar/article/edit/123 or /bazbam/person/edit/345

for each of the resources. Is this possible with the resources method, or must I hand-craft these? I will not know the possible values for :edition ahead of time; these get looked up in a before_filter in my ApplicationController.

Is this all I need to do?

```<code>scope ':edition' do
  resources :articles
  resources :matches
  resources :teams
end
</code>```

UPDATE: When using the scope directive above, I get routes like I want:

```<code>    articles GET    /:edition/articles(.:format)          {:action=>"index", :controller=>"articles"}
             POST   /:edition/articles(.:format)          {:action=>"create", :controller=>"articles"}
 new_article GET    /:edition/articles/new(.:format)      {:action=>"new", :controller=>"articles"}
edit_article GET    /:edition/articles/:id/edit(.:format) {:action=>"edit", :controller=>"articles"}
     article GET    /:edition/articles/:id(.:format)      {:action=>"show", :controller=>"articles"}
             PUT    /:edition/articles/:id(.:format)      {:action=>"update", :controller=>"articles"}
             DELETE /:edition/articles/:id(.:format)      {:action=>"destroy", :controller=>"articles"}
     matches GET    /:edition/matches(.:format)           {:action=>"index", :controller=>"matches"}
             POST   /:edition/matches(.:format)           {:action=>"create", :controller=>"matches"}
   new_match GET    /:edition/matches/new(.:format)       {:action=>"new", :controller=>"matches"}
  edit_match GET    /:edition/matches/:id/edit(.:format)  {:action=>"edit", :controller=>"matches"}
       match GET    /:edition/matches/:id(.:format)       {:action=>"show", :controller=>"matches"}
             PUT    /:edition/matches/:id(.:format)       {:action=>"update", :controller=>"matches"}
             DELETE /:edition/matches/:id(.:format)       {:action=>"destroy", :controller=>"matches"}
       teams GET    /:edition/teams(.:format)             {:action=>"index", :controller=>"teams"}
             POST   /:edition/teams(.:format)             {:action=>"create", :controller=>"teams"}
    new_team GET    /:edition/teams/new(.:format)         {:action=>"new", :controller=>"teams"}
   edit_team GET    /:edition/teams/:id/edit(.:format)    {:action=>"edit", :controller=>"teams"}
        team GET    /:edition/teams/:id(.:format)         {:action=>"show", :controller=>"teams"}
             PUT    /:edition/teams/:id(.:format)         {:action=>"update", :controller=>"teams"}
             DELETE /:edition/teams/:id(.:format)         {:action=>"destroy", :controller=>"teams"}
</code>```

I'm now able to reference :edition in my ApplicationController:

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :get_edition

  def get_edition
    @edition = Edition.first(:conditions => { :FriendlyName => params[:edition] } )
  end

end
</code>```

Now I just want to make sure this is the best way to accomplish this.

答:
If you don't know the possible values for edition - then you can't use namespaces which seem like they might have solved this issue.

That said, I'd just handcraft them - your case here seems like the ideal case foregoing resources and going straight to a handcrafted path.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to have a variable namespace? I have restful resources like the following:

resources :articles
resources :persons

But I need to scope these inside a variable namespace, such that it responds to URLs of the form:

':edition/:controller/:action/:id'

for example:

/foobar/article/edit/123 or /bazbam/person/edit/345

for each of the resources. Is this possible with the resources method, or must I hand-craft these? I will not know the possible values for :edition ahead of time; these get looked up in a before_filter in my ApplicationController.

Is this all I need to do?

scope ':edition' do
  resources :articles
  resources :matches
  resources :teams
end

UPDATE: When using the scope directive above, I get routes like I want:

    articles GET    /:edition/articles(.:format)          {:action=>"index", :controller=>"articles"}
             POST   /:edition/articles(.:format)          {:action=>"create", :controller=>"articles"}
 new_article GET    /:edition/articles/new(.:format)      {:action=>"new", :controller=>"articles"}
edit_article GET    /:edition/articles/:id/edit(.:format) {:action=>"edit", :controller=>"articles"}
     article GET    /:edition/articles/:id(.:format)      {:action=>"show", :controller=>"articles"}
             PUT    /:edition/articles/:id(.:format)      {:action=>"update", :controller=>"articles"}
             DELETE /:edition/articles/:id(.:format)      {:action=>"destroy", :controller=>"articles"}
     matches GET    /:edition/matches(.:format)           {:action=>"index", :controller=>"matches"}
             POST   /:edition/matches(.:format)           {:action=>"create", :controller=>"matches"}
   new_match GET    /:edition/matches/new(.:format)       {:action=>"new", :controller=>"matches"}
  edit_match GET    /:edition/matches/:id/edit(.:format)  {:action=>"edit", :controller=>"matches"}
       match GET    /:edition/matches/:id(.:format)       {:action=>"show", :controller=>"matches"}
             PUT    /:edition/matches/:id(.:format)       {:action=>"update", :controller=>"matches"}
             DELETE /:edition/matches/:id(.:format)       {:action=>"destroy", :controller=>"matches"}
       teams GET    /:edition/teams(.:format)             {:action=>"index", :controller=>"teams"}
             POST   /:edition/teams(.:format)             {:action=>"create", :controller=>"teams"}
    new_team GET    /:edition/teams/new(.:format)         {:action=>"new", :controller=>"teams"}
   edit_team GET    /:edition/teams/:id/edit(.:format)    {:action=>"edit", :controller=>"teams"}
        team GET    /:edition/teams/:id(.:format)         {:action=>"show", :controller=>"teams"}
             PUT    /:edition/teams/:id(.:format)         {:action=>"update", :controller=>"teams"}
             DELETE /:edition/teams/:id(.:format)         {:action=>"destroy", :controller=>"teams"}

I'm now able to reference :edition in my ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :get_edition

  def get_edition
    @edition = Edition.first(:conditions => { :FriendlyName => params[:edition] } )
  end

end

Now I just want to make sure this is the best way to accomplish this.


问:
what is the difference between spring data save and hibernate save?
what is the difference between spring data save and hibernate save? Do they work in same way?

答:
You'll understand this better if you understand exactly what the relationship is between JPA, Hibernate and Spring Data JPA.

JPA (Java Persistence API) is a standard interface specification for doing ORM (object-relational mapping) in Java. Note that it does not by itself implement the interface. You need a library that implements the JPA specification to be able to use it in your software.

Hibernate is an implementation of JPA - it's a library that implements the JPA specification.

Spring Data JPA is a subproject of the Spring Framework, which makes it easier to work with JPA and integrate it into the rest of the Spring Framework.

If you use Spring Data JPA, you also need to have an implementation of JPA in your project, such as Hibernate.

You use the interfaces and classes that Spring Data JPA provides, and it talks to the underlying JPA implementation (Hibernate) to actually talk to the database.

Saving an entity through Spring Data JPA will ultimately call Hibernate to save the entity, so in the end the effect is the same.

However: If you are using Spring Data JPA, you should not be using Hibernate directly. In fact, you should not have any direct references at all to Hibernate in your own code. By directly using Hibernate in your code you would be bypassing Spring Data JPA entirely.

ContentLicense: CC BY-SA 4.0


问:
Gracefully migrate from SSRS2014/IE to SSRS2016/Edge
I have a chicken-egg-problem when upgrading from SSRS2014 to SSRS2016.

I cannot move to the new reportviewer because I still have users on
IE. The new report viewer cannot print nicely on Internet Explorer:
if you click print, you can download a pdf and THEN print it.
Due to the large amount of reports we print, this is no feasable option.

I cannot migrate away from Internet Explorer because of the old report
viewer: The ActiveX print control only works in Internet Explorer.

So I want to migrate to the new report server, yet show the reports through the old viewer for IE-users. So my test web server has both the new and the old reporting component. If the client uses Internet Explorer, I serve the old one. Otherwise, they get the new one.

In my test environment, reports from SSRS 2016 are rendered correctly by the old reporting control. (Microsoft.ReportViewer.WebForms version 11.0.0.0) However, when I try to print, the client displays a dialog box "Unable to load client print control"

On my server, an exception is thrown:

```<code>The report server could not find the internal resource '2015.130.1601.05rsclientprint.cab'. (rsInternalResourceNotFoundError)

[ReportServerException: The report server could not find the internal resource '2015.130.1601.05rsclientprint.cab'. (rsInternalResourceNotFoundError)]
   Microsoft.Reporting.WebForms.SoapReportExecutionService.WritePrintCab(ClientArchitecture arch, Stream stream) +797
   Microsoft.Reporting.WebForms.ServerReport.WritePrintCab(ClientArchitecture arch, Stream stream) +75
   Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +304
</code>```

I know there is a new reporting control, making the ActiveX print control obsolete. However, I'd like to prevent a big bang implementation. Printing with the old control only works on Internet Explorer, so all users use IE. Printing with the new control DOESN'T work with IE.

(If 100+ users print 50+ reports a day, having to download a pdf and print that is a BIG difference.)

https://learn.microsoft.com/en-us/sql/reporting-services/report-server/enable-and-disable-client-side-printing-for-reporting-services says:
"Previous versions of Reporting Services used an ActiveX control that required downloading to the client computer from the report server. If you upgrade your report server to SQL Server 2016, the print control is not removed from the report server or client computers."

This suggests that ActiveX printing is also possible with the new server, probably through the old Report viewer control. If that works, I can put the new control next to the old one, and gradually migrate my users to a modern browser.

Did anybody get this to work without restarting and installing SQL Server 2014, and upgrading?

答:
To migrate SSRS Reports from 2014 to 2016. Simply follow below steps:

Backup and restore original databases

Backup encryption key

Install Ssrs 2016 on new server with managed service account.

Restore databases and remove server key entry from key table in the report database.

Configure Ssrs 2016 to look at new restored databases on same new instance.

Restore keys from backup.

Or visit this link :https://www.mssqltips.com/sqlservertip/2692/migrating-sql-reporting-services-to-a-new-server-by-moving-the-reporting-services-databases/

Body:
I have a chicken-egg-problem when upgrading from SSRS2014 to SSRS2016.

I cannot move to the new reportviewer because I still have users on
IE. The new report viewer cannot print nicely on Internet Explorer:
if you click print, you can download a pdf and THEN print it.
Due to the large amount of reports we print, this is no feasable option.

I cannot migrate away from Internet Explorer because of the old report
viewer: The ActiveX print control only works in Internet Explorer.

So I want to migrate to the new report server, yet show the reports through the old viewer for IE-users. So my test web server has both the new and the old reporting component. If the client uses Internet Explorer, I serve the old one. Otherwise, they get the new one.

In my test environment, reports from SSRS 2016 are rendered correctly by the old reporting control. (Microsoft.ReportViewer.WebForms version 11.0.0.0) However, when I try to print, the client displays a dialog box "Unable to load client print control"

On my server, an exception is thrown:

The report server could not find the internal resource '2015.130.1601.05rsclientprint.cab'. (rsInternalResourceNotFoundError)

[ReportServerException: The report server could not find the internal resource '2015.130.1601.05rsclientprint.cab'. (rsInternalResourceNotFoundError)]
   Microsoft.Reporting.WebForms.SoapReportExecutionService.WritePrintCab(ClientArchitecture arch, Stream stream) +797
   Microsoft.Reporting.WebForms.ServerReport.WritePrintCab(ClientArchitecture arch, Stream stream) +75
   Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +304

I know there is a new reporting control, making the ActiveX print control obsolete. However, I'd like to prevent a big bang implementation. Printing with the old control only works on Internet Explorer, so all users use IE. Printing with the new control DOESN'T work with IE.

(If 100+ users print 50+ reports a day, having to download a pdf and print that is a BIG difference.)

https://learn.microsoft.com/en-us/sql/reporting-services/report-server/enable-and-disable-client-side-printing-for-reporting-services says:
"Previous versions of Reporting Services used an ActiveX control that required downloading to the client computer from the report server. If you upgrade your report server to SQL Server 2016, the print control is not removed from the report server or client computers."

This suggests that ActiveX printing is also possible with the new server, probably through the old Report viewer control. If that works, I can put the new control next to the old one, and gradually migrate my users to a modern browser.

Did anybody get this to work without restarting and installing SQL Server 2014, and upgrading?


问:
can't get value from spring, web-flow
I'm a newbie in spring framework and web-flow,
I'm trying to get the value of a textarea, but still couldn't get it.
in my someFlow.xml file I declared my variable with

<var name="varName" class="java.lang.String"/>

in my xhtml page the textarea is defined as follows:

<injsf:inputtextarea id="richText_varName" label="#{lbl.textarea}" rows="1" size="50" required="true" value="#{varName}"/>

when I type

 <evaluate expression="someClass.someMethod(varName)"/>

the variable varName is blank, but when I type

 <evaluate expression="someClass.someMethod('some Text')"/>
I can get the text.

what sould be the problem?

why I cant get the value from the textarea

答:
Thank you Bozho, your comment let me think different :)

from the <injsf:textarea> component I was supposed to get the value with entityValue, not just value

```
<injsf:inputtextarea id="richText_aciklama" label="#{lbl.label.gnl.aciklama}" rows="1" size="50" required="true" entityValue="#{fh.aciklama}"/>
```

Title: can't get value from spring, web-flow

Body:
Thank you Bozho, your comment let me think different :)

from the <injsf:textarea> component I was supposed to get the value with entityValue, not just value

<injsf:inputtextarea id="richText_aciklama" label="#{lbl.label.gnl.aciklama}" rows="1" size="50" required="true" entityValue="#{fh.aciklama}"/>


问:
Difference in Image constructors
In JavaFX 8, what is the difference between loading an Image with the InputStream constructor and loading an Image with the url constructor.

If I use

```<code>private Image getImage(String s){
    return new Image(getClass().getResourceAsStream("/fruit/" +s+".png"));
}
</code>```

Does it do the same thing as

```<code>private Image getImage(String s){
    return new Image("/fruit/" +s+".png");
}
</code>```

First I thought the latter wouldn't work when I compiled it as a jar but it does.

Here is a link to the API of Image.

答: In my opinion, the biggest difference is where the system will search for the file. If you export your project into an executable JAR file, you will notice that Image(InputStream) will allow you to search within your JAR file, while Image(String) will only allow you to search outside your JAR file.

Title: Difference in Image constructors

Body:
In JavaFX 8, what is the difference between loading an Image with the InputStream constructor and loading an Image with the url constructor.

If I use

private Image getImage(String s){
    return new Image(getClass().getResourceAsStream("/fruit/" +s+".png"));
}

Does it do the same thing as

private Image getImage(String s){
    return new Image("/fruit/" +s+".png");
}

First I thought the latter wouldn't work when I compiled it as a jar but it does.

Here is a link to the API of Image.


问:
Multiprocessing - map over list, killing processes that stall above timeout limit
I have a list of elements that I want to modify using multiprocessing. The issue is that for some particular inputs (unobservable prior to attempting), part of the my function stalls. I've shown this conceptually with the code below, where the function sometimes_stalling_processing() will occasionally stall indefinitely.

To put this into context, I'm processing a bunch of links using a web scraper and some of these links stall even with the use of timeout in the requests module. I've attempted different approaches (e.g. using eventlet), but come to the conclusion that it's perhaps easier to handle it at the multiprocessing level.

```<code>def stable_processing(obs):
    ...
    return processed_obs

def sometimes_stalling_processing(obs):
    ...
    return processed_obs

def extract_info(obs):
    new_obs = stable_processing(obs)
    try:
        new_obs = sometimes_stalling_processing(obs)
    except MyTimedOutError: # error doesn't exist, just here for conceptual purposes
        pass
    return new_obs

pool = Pool(processes=n_threads)
processed_dataset = pool.map(extract_info, dataset)
pool.close()
pool.join()
</code>```

This question (How can I abort a task in a multiprocessing.Pool after a timeout?) seems very similar, but I've been unable to convert it to work with map instead of apply. I've also tried using the eventlet package, but that doesn't work. Note that I'm using Python 2.7.

How do I make pool.map() timeout on individual observations and kill sometimes_stalling_processing?

答:
You can take a look at the pebble library.

```<code>from pebble import ProcessPool
from concurrent.futures import TimeoutError

def sometimes_stalling_processing(obs):
    ...
    return processed_obs

with ProcessPool() as pool:
    future = pool.map(sometimes_stalling_processing, dataset, timeout=10)

    iterator = future.result()

    while True:
        try:
            result = next(iterator)
        except StopIteration:
            break
        except TimeoutError as error:
            print("function took longer than %d seconds" % error.args[1])
</code>```

More examples in the documentaion.

Body:
I have a list of elements that I want to modify using multiprocessing. The issue is that for some particular inputs (unobservable prior to attempting), part of the my function stalls. I've shown this conceptually with the code below, where the function sometimes_stalling_processing() will occasionally stall indefinitely.

To put this into context, I'm processing a bunch of links using a web scraper and some of these links stall even with the use of timeout in the requests module. I've attempted different approaches (e.g. using eventlet), but come to the conclusion that it's perhaps easier to handle it at the multiprocessing level.

def stable_processing(obs):
    ...
    return processed_obs

def sometimes_stalling_processing(obs):
    ...
    return processed_obs

def extract_info(obs):
    new_obs = stable_processing(obs)
    try:
        new_obs = sometimes_stalling_processing(obs)
    except MyTimedOutError: # error doesn't exist, just here for conceptual purposes
        pass
    return new_obs

pool = Pool(processes=n_threads)
processed_dataset = pool.map(extract_info, dataset)
pool.close()
pool.join()

This question (How can I abort a task in a multiprocessing.Pool after a timeout?) seems very similar, but I've been unable to convert it to work with map instead of apply. I've also tried using the eventlet package, but that doesn't work. Note that I'm using Python 2.7.

How do I make pool.map() timeout on individual observations and kill sometimes_stalling_processing?

Body:
You can take a look at the pebble library.

from pebble import ProcessPool
from concurrent.futures import TimeoutError

def sometimes_stalling_processing(obs):
    ...
    return processed_obs

with ProcessPool() as pool:
    future = pool.map(sometimes_stalling_processing, dataset, timeout=10)

    iterator = future.result()

    while True:
        try:
            result = next(iterator)
        except StopIteration:
            break
        except TimeoutError as error:
            print("function took longer than %d seconds" % error.args[1])

More examples in the documentaion.


问:
Yii2 Count all record in table
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.</p>

```<code>$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();
</code>```

答:
```<code>echo reportDetails::find()->where(['report_id'=> $id])->count(),
</code>```

Title: Yii2 Count all record in table

Body:
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.

$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();


问:
In SQL Server, how do I reset the id column of my table back to 1?
My table has an int-based identity column in SQL Server.

Since I have removed entries from this table, the id's no longer begin at 1.

How do I reset the id column of my table back to 1?

答:
This is actually not a bug but a feature of SQL server 2012. This happens when ever you restart the SQL instance.

The jumping value depends on the datatype, for int it's 1000 and for bigint its 10,000. (this is the cache allocated for identity which is lost on restarting of instance)

Please refer this link for a preferred solution for this.


答:
Though you should not load so many records at once, it will make your server insecure and you may go out of resources if so many multiple request are made at once. You should try Ajax based Datatable.

https://datatables.net/examples/ajax/objects.html

Link above uses the AJAX call to load data so that you don't have to query all 60,000 rows.

Title: datatable does not support if more than 60000 records are being fetched


问:
How to Post a UILocalNotifivcation only once in iOS
Im posting a notification in iOS, I dont want to repeat the notification code i have used is.

```<code>let notification = UILocalNotification()
notification.timeZone = NSTimeZone.local
//calculation of dateTime
notification.fireDate = dateTime as Date?

notification.repeatInterval = 0

notification.alertBody = "Body"
notification.userInfo = ["title": "Notify", "type": "title", "5436" : "Notify"]
</code>```

In that condition my notification was not firing. When I give like

```<code>notification.repeatInterval = NSCalendar.Unit.day
</code>```

It is firing.. Is this a feature or issue? How can i post a notification without repeat interval

答:
Soultion 1:
You can use dispatch_once:

```<code>static var token: dispatch_once_t = 0

dispatch_once(&token) {
  NSLog("Do it once")
}
</code>```

Solution 2:

Taken from Apple documentation:

If you assign an calendar unit such as weekly (NSWeekCalendarUnit) or
  yearly (NSYearCalendarUnit), the system reschedules the notification
  for delivery at the specified interval. The default value is 0, which
  means don't repeat.

I assume you want to cancel the notification with the repeating interval, you can do that in two ways:

Cancel all the notifications.

Cancel only that notification.

The first option is easy, use:

cancelAllLocalNotifications
In your app delegate.

The second one requires more work. You need to go through the pending notifications (use scheduledLocalNotifications) and cancel the notification.

In order to know which notifications is going to be canceled you can use the userInfo property when you set the notification. For example set an unique ID for every notification so when you cancel that notification you simply compare that ID with all the IDs in your scheduledLocalNotifications array.

Body:
Im posting a notification in iOS, I dont want to repeat the notification code i have used is.

let notification = UILocalNotification()
notification.timeZone = NSTimeZone.local
//calculation of dateTime
notification.fireDate = dateTime as Date?

notification.repeatInterval = 0

notification.alertBody = "Body"
notification.userInfo = ["title": "Notify", "type": "title", "5436" : "Notify"]

In that condition my notification was not firing. When I give like

notification.repeatInterval = NSCalendar.Unit.day

It is firing.. Is this a feature or issue? How can i post a notification without repeat interval

Body:
Soultion 1:
You can use dispatch_once:

static var token: dispatch_once_t = 0

dispatch_once(&token) {
  NSLog("Do it once")
}

Solution 2:

Taken from Apple documentation:

If you assign an calendar unit such as weekly (NSWeekCalendarUnit) or
  yearly (NSYearCalendarUnit), the system reschedules the notification
  for delivery at the specified interval. The default value is 0, which
  means don't repeat.

I assume you want to cancel the notification with the repeating interval, you can do that in two ways:

Cancel all the notifications.

Cancel only that notification.

The first option is easy, use:

cancelAllLocalNotifications
In your app delegate.

The second one requires more work. You need to go through the pending notifications (use scheduledLocalNotifications) and cancel the notification.

In order to know which notifications is going to be canceled you can use the userInfo property when you set the notification. For example set an unique ID for every notification so when you cancel that notification you simply compare that ID with all the IDs in your scheduledLocalNotifications array.


问:
Laravel Update not working
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();
</code>```

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();
</code>```

Can you help me why first code is not working.

答:
Use boolean type, no integer 1: $adminDetail->fill(['is_delete' => true])->save();

And you can use as property without fill method and you do not need accept is_delete in the $fillable array:

```<code>$adminDetail->is_delete = true;
$adminDetail->save();
</code>```

Title: Laravel Update not working

Body:
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();

Can you help me why first code is not working.

Body:
Use boolean type, no integer 1: $adminDetail->fill(['is_delete' => true])->save();

And you can use as property without fill method and you do not need accept is_delete in the $fillable array:

$adminDetail->is_delete = true;
$adminDetail->save();


问:
jQuery UI Autocomplete: how do you start an asynchronous process and quit it before it finishes
I am using jQuery UI Autocomplete to build a search interface.

I have defined a custom function which returns search results and updates them automatically as keys are pressed however, sometimes this custom function doesn't complete before the next key is pressed (i.e. its still processing "Wash" when I have already written "Washi" (on the way to writing "Washington").

I would like every call to the autocomplete "source" event to cancel the previous function(Wash) and start the new function(Washi). With the next call cancelling function(Washi) and starting function (Washin) and so on.

How is this kind of thing done?

答:
You should be able to do something like this:

```<code>var lastXhr;
$( "#myAutocomplete" ).autocomplete({
    source: function( request, response ) {
        if (lastXhr) lastXhr.abort();
        lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
            if ( xhr === lastXhr ) {
                response( data );
            }
        });
    }
});
</code>```

the lastXhr var stores the most current xhr request.  If there is one set and the source function is called then it aborts the lastXhr request and makes a new one.  When the ajax request returns if make sure that it matches the lastXhr, if not then it doesn't call the response() function.

Body:
You should be able to do something like this:

var lastXhr;
$( "#myAutocomplete" ).autocomplete({
    source: function( request, response ) {
        if (lastXhr) lastXhr.abort();
        lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
            if ( xhr === lastXhr ) {
                response( data );
            }
        });
    }
});

the lastXhr var stores the most current xhr request.  If there is one set and the source function is called then it aborts the lastXhr request and makes a new one.  When the ajax request returns if make sure that it matches the lastXhr, if not then it doesn't call the response() function.


问:
Test ansible playbooks for deprecated syntax against a specific version
I inherited some legacy code from a different team.

These ansible playbooks run fine with current version of ansible 2.3 but they make use of syntax which is way old and has few syntax which was deprecated in older versions 1.6 !!!

So I want to upgrade it to adopt to the latest version, in order to take advantage of some new features of ansible.

Now since ansible has not still removed the deprecated syntax, is there a way so that i can run in strict mode so that it treats deprecated syntax as unsupported. This way I can identify all the deprecated lines as well as I can run a sanity test.

答:
I'm not aware of such feature in Ansible.

There's --syntax-check option for ansible-playbook, but this doesn't show deprecation warnings as they occur in runtime.

You can patch your Ansible installation a bit.

Add removed = True at the very beginning of display.deprecated method here.

This way Ansible will treat every deprecated feature as removed one and raise fatal error.


问:
Delete Rows in apache spark using java
Need to delete second row in that dataset i am new to apache spark can anyone help me to resolve.
below is the code:

```<code>  public class DeleteRow {
         public static void main(String[] args) {
          System.setProperty("hadoop.home.dir", "C:\\winutils");
          JavaSparkContext sc = new JavaSparkContext(new SparkConf().setAppName("JoinFunctions").setMaster("local[*]"));
          SQLContext sqlContext = new SQLContext(sc);
          SparkSession spark = SparkSession.builder().appName("JavaTokenizerExample").getOrCreate();

          List<Row> data = Arrays.asList(
            RowFactory.create(1,"Hi I heard about Spark"),
            RowFactory.create(2,"I wish Java could use case classes"),
            RowFactory.create(3,"Logistic,regression,models,are,neat"));

          StructType schema = new StructType(new StructField[] {
            new StructField("label", DataTypes.IntegerType, false,
              Metadata.empty()),
          new StructField("sentence", DataTypes.StringType, false,
            Metadata.empty()) });

            String ins  = data.get(1).toString();
            System.out.println(ins);

          Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
        sentenceDataFrame.drop(data.get(1).toString());
</code>```

Any help appreciated.

答:
Use a FilterFunction.

I wrote a JUnit Test to help you out.

```<code>@Test
public void sampleDeleteRowTest() throws Exception {
    List<Row> data = Arrays.asList(
            RowFactory.create(1, "Hi I heard about Spark"),
            RowFactory.create(2, "I wish Java could use case classes"),
            RowFactory.create(3, "Logistic,regression,models,are,neat"));

    StructType schema = new StructType(new StructField[]{
            new StructField("label", DataTypes.IntegerType, false,
                    Metadata.empty()),
            new StructField("sentence", DataTypes.StringType, false,
                    Metadata.empty())});

    String ins = data.get(1).toString();
    System.out.println(ins);

    Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
    long size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 3);

    sentenceDataFrame = sentenceDataFrame.filter(new FilterFunction<Row>() {
        @Override
        public boolean call(Row row) throws Exception {
            Integer label = row.getInt(0);
            return label != 2;
        }
    });

    size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 2);
}
</code>```

https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Dataset.html#filter(org.apache.spark.api.java.function.FilterFunction)

https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/api/java/function/FilterFunction.html

Alternatively, you can use a Lambda function to achieve the same desired result:

```<code>sentenceDataFrame = sentenceDataFrame.filter((FilterFunction<Row>) r -> (r).getInt(0) != 2);
</code>```

Title: Delete Rows in apache spark using java

Body:
Need to delete second row in that dataset i am new to apache spark can anyone help me to resolve.
below is the code:

  public class DeleteRow {
         public static void main(String[] args) {
          System.setProperty("hadoop.home.dir", "C:\\winutils");
          JavaSparkContext sc = new JavaSparkContext(new SparkConf().setAppName("JoinFunctions").setMaster("local[*]"));
          SQLContext sqlContext = new SQLContext(sc);
          SparkSession spark = SparkSession.builder().appName("JavaTokenizerExample").getOrCreate();

          List<Row> data = Arrays.asList(
            RowFactory.create(1,"Hi I heard about Spark"),
            RowFactory.create(2,"I wish Java could use case classes"),
            RowFactory.create(3,"Logistic,regression,models,are,neat"));

          StructType schema = new StructType(new StructField[] {
            new StructField("label", DataTypes.IntegerType, false,
              Metadata.empty()),
          new StructField("sentence", DataTypes.StringType, false,
            Metadata.empty()) });

            String ins  = data.get(1).toString();
            System.out.println(ins);

          Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
        sentenceDataFrame.drop(data.get(1).toString());

Any help appreciated.

Body:
Use a FilterFunction.

I wrote a JUnit Test to help you out.

@Test
public void sampleDeleteRowTest() throws Exception {
    List<Row> data = Arrays.asList(
            RowFactory.create(1, "Hi I heard about Spark"),
            RowFactory.create(2, "I wish Java could use case classes"),
            RowFactory.create(3, "Logistic,regression,models,are,neat"));

    StructType schema = new StructType(new StructField[]{
            new StructField("label", DataTypes.IntegerType, false,
                    Metadata.empty()),
            new StructField("sentence", DataTypes.StringType, false,
                    Metadata.empty())});

    String ins = data.get(1).toString();
    System.out.println(ins);

    Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
    long size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 3);

    sentenceDataFrame = sentenceDataFrame.filter(new FilterFunction<Row>() {
        @Override
        public boolean call(Row row) throws Exception {
            Integer label = row.getInt(0);
            return label != 2;
        }
    });

    size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 2);
}

https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Dataset.html#filter(org.apache.spark.api.java.function.FilterFunction)

https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/api/java/function/FilterFunction.html

Alternatively, you can use a Lambda function to achieve the same desired result:

sentenceDataFrame = sentenceDataFrame.filter((FilterFunction<Row>) r -> (r).getInt(0) != 2);


问:
Docker centos7 systemctl deos not work : Failed to connect D-bus
I am trying to run elasticsearch on docker.

My features like below

host system : OSX 10.12.5

docker : 17.05.0-ce

docker operating image : centos:latest

I was following this article, but it stuck with systemctl daemon-reload.

I found CentOS official respond about this D-bus bug, but when I ran docker run command it shows the message below.

[!!!!!!] Failed to mount API filesystems, freezing.

How could I solve this problem?

FYI, Here is Dockerfile what I build image

```<code>FROM centos
MAINTAINER juneyoung <juneyoung@hanmail.net>

ARG u=elastic
ARG uid=1000
ARG g=elastic
ARG gid=1000
ARG p=elastic

# add USER
RUN groupadd -g ${gid} ${g}
RUN useradd -d /home/${u} -u ${uid} -g ${g} -s /bin/bash ${u}

# systemctl settings from official Centos github
# https://github.com/docker-library/docs/tree/master/centos#systemd-integration
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]

# yum settings
RUN yum -y update
RUN yum -y install java-1.8.0-openjdk.x86_64
ENV JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64/jre/

# install wget
RUN yum install -y wget

# install net-tools : netstat, ifconfig
RUN yum install -y net-tools

# Elasticsearch install
ENV ELASTIC_VERSION=5.4.0
RUN rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${ELASTIC_VERSION}.rpm
RUN rpm -ivh elasticsearch-${ELASTIC_VERSION}.rpm

CMD ["/usr/sbin/init"]
</code>```

and I have ran with command

docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro --name=elastic2 elastic2

答:
First, thanks to @Robert.
I did not think it that way.

All I have to do is just edit my CMD command.

Change that to

CMD["elasticsearch"]

However, have to some chores to access from the browser.
refer this elasticsearch forum post.

Body:
I am trying to run elasticsearch on docker.

My features like below

host system : OSX 10.12.5

docker : 17.05.0-ce

docker operating image : centos:latest

I was following this article, but it stuck with systemctl daemon-reload.

I found CentOS official respond about this D-bus bug, but when I ran docker run command it shows the message below.

[!!!!!!] Failed to mount API filesystems, freezing.

How could I solve this problem?

FYI, Here is Dockerfile what I build image

FROM centos
MAINTAINER juneyoung <juneyoung@hanmail.net>

ARG u=elastic
ARG uid=1000
ARG g=elastic
ARG gid=1000
ARG p=elastic

# add USER
RUN groupadd -g ${gid} ${g}
RUN useradd -d /home/${u} -u ${uid} -g ${g} -s /bin/bash ${u}

# systemctl settings from official Centos github
# https://github.com/docker-library/docs/tree/master/centos#systemd-integration
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]

# yum settings
RUN yum -y update
RUN yum -y install java-1.8.0-openjdk.x86_64
ENV JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64/jre/

# install wget
RUN yum install -y wget

# install net-tools : netstat, ifconfig
RUN yum install -y net-tools

# Elasticsearch install
ENV ELASTIC_VERSION=5.4.0
RUN rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${ELASTIC_VERSION}.rpm
RUN rpm -ivh elasticsearch-${ELASTIC_VERSION}.rpm

CMD ["/usr/sbin/init"]

and I have ran with command

docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro --name=elastic2 elastic2


问:
ElasticSearch cannot find newly written document
In my logic, application writes documents into elasticsearch and it sometimes tries to read it from another thread. But when it tries to read it, query is not returning any hits.

I assume that in POST request (insertion), when I get 201 , it means the document is created.

Is my assumption wrong? What am I missing in here?

Thx for your responses

Neron

EDIT:

save response {“_index”:“customers”,“_type”:“customers”,“_id”:“123",“_version”:1,“result”:“created”,“_shards”:{“total”:2,“successful”:2,“failed”:0},“created”:true}

query request:

```<code>{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "id": "123"
          }
        }
      ]
    }
  }
}
</code>```

query-response:

```<code>{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
</code>```

after some time, it gets the response and hits is not now then.

答:
I think you are doing GET request, that's why getting 200 status code. If it is POST call then it should be 201 status code.

Try this query.

```<code>{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "_id": "123"
          }
        }
      ]
    }
  }
}
</code>```

Body:
In my logic, application writes documents into elasticsearch and it sometimes tries to read it from another thread. But when it tries to read it, query is not returning any hits.

I assume that in POST request (insertion), when I get 201 , it means the document is created.

Is my assumption wrong? What am I missing in here?

Thx for your responses

Neron

EDIT:

save response {“_index”:“customers”,“_type”:“customers”,“_id”:“123",“_version”:1,“result”:“created”,“_shards”:{“total”:2,“successful”:2,“failed”:0},“created”:true}

query request:

{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "id": "123"
          }
        }
      ]
    }
  }
}

query-response:

{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}

after some time, it gets the response and hits is not now then.

Body:
I think you are doing GET request, that's why getting 200 status code. If it is POST call then it should be 201 status code.

Try this query.

{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "_id": "123"
          }
        }
      ]
    }
  }
}


问:
Find out whether the Bluetooth device detected is a printer device
I am developing an Android printing application using Cordova using the 'Cordova-Plugin-Bluetooth-Printer' plugin. While searching for Bluetooth devices, the result contains many devices. I would like to list only the printer devices in my result list. Is it possible to find whether the device detected is a printer device or not?</p>

答: There is no such method to identify the printer devices. But you can make it possible by using unique name of the Bluetooth device. If you found the Bluetooth devices starting with that device name,you can take necessary actions.We got the same requirement like you. But we finally ended up with the mentioned solution. </p>


问:
Starting multiple sessions in PHP
I'm trying to start 3 sessions when the user logs in.

But the only session that is being started is the $email=$_POST['email']

Here is my code.

```<code>if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //checks the database where this user exist or not

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$student;
        $_SESSION['OfferingID']=$Offering;

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}
</code>```

答:
Assuming the studentID and offering are from the database record, you need to fetch the data and extract those fields from the record fetched.

Something like...

```<code>    $student = mysqli_fetch_assoc($query_run);
    $_SESSION['email']=$email;
    $_SESSION['StudentID']=$student['studentID'];
    $_SESSION['OfferingID']=$student['OfferingID'];
</code>```

Title: Starting multiple sessions in PHP

Body:
I'm trying to start 3 sessions when the user logs in.

But the only session that is being started is the $email=$_POST['email']

Here is my code.

if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //checks the database where this user exist or not

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$student;
        $_SESSION['OfferingID']=$Offering;

        header('location: profile.php'); //
    }
    else
    {
        echo '';
    }
}

Body:
Assuming the studentID and offering are from the database record, you need to fetch the data and extract those fields from the record fetched.

Something like...

    $student = mysqli_fetch_assoc($query_run);
    $_SESSION['email']=$email;
    $_SESSION['StudentID']=$student['studentID'];
    $_SESSION['OfferingID']=$student['OfferingID'];


问:
PRINTDLG OR PAGESETUPDLG
i am trying to launch Printdlg() in my wince device but it is showing me linking error while building . this is the way i am doing it..

```<code>/// using pagesetupdlg....

PAGESETUPDLG info;
    memset(&info,0,sizeof(info));

    info.lStructSize=sizeof(info);

    PageSetupDlg(&info);
</code>```

or

```<code>////using printdlg...
PRINTDLG info;
    memset(&info,0,sizeof(info));

    info.lStructSize=sizeof(info);

    PrintDlg(&info);
</code>```

in both case it is showing me ---

error LNK2019: unresolved external
  symbol PageSetupDlgW referenced in
  function "public: void __cdecl
  CAboutDlg::OnBnClickedButton1(void)"
  (?OnBnClickedButton1@CAboutDlg@@QAAXXZ)
  PrinterTest.obj

plesae suggest me the solution...
regards,
mukesh

答:
PageSetupDlg is definitely supported in the OS so that leaves two questions:

Are you linking to commdlg.lib?

Is the function included in your OS image/device SDK?

If #1 is true, then it's likely that #2 is false - at least it's not in the SDK.  First, go look at the OS design.  If you don't have access to that, you could try manually pulling it in - I'd try declaring it as an extern first and if that fails, try GetProcAddress.

Title: PRINTDLG OR PAGESETUPDLG

Body:
i am trying to launch Printdlg() in my wince device but it is showing me linking error while building . this is the way i am doing it..

/// using pagesetupdlg....

PAGESETUPDLG info;
    memset(&info,0,sizeof(info));

    info.lStructSize=sizeof(info);

    PageSetupDlg(&info);

or

////using printdlg...
PRINTDLG info;
    memset(&info,0,sizeof(info));

    info.lStructSize=sizeof(info);

    PrintDlg(&info);

in both case it is showing me ---

error LNK2019: unresolved external
  symbol PageSetupDlgW referenced in
  function "public: void __cdecl
  CAboutDlg::OnBnClickedButton1(void)"
  (?OnBnClickedButton1@CAboutDlg@@QAAXXZ)
  PrinterTest.obj

plesae suggest me the solution...
regards,
mukesh


答:
first get $student and $offering inside condition in your code like this

```<code>if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //fetch array and get values for studentid and offeringid
        $student = mysqli_fetch_assoc($query_run);
    $_SESSION['email']=$email;
    $_SESSION['StudentID']=$student['studentID'];
    $_SESSION['OfferingID']=$student['OfferingID'];

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}
</code>```

here i set  check again

Title: Starting multiple sessions in PHP

Body:
first get $student and $offering inside condition in your code like this

if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //fetch array and get values for studentid and offeringid
        $student = mysqli_fetch_assoc($query_run);
    $_SESSION['email']=$email;
    $_SESSION['StudentID']=$student['studentID'];
    $_SESSION['OfferingID']=$student['OfferingID'];

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}

here i set  check again


问:
Not be able to register on spotify tool
I'm trying to register on spotify either create an account or facebook login. But not get login.

When I try login by facebook then return message

You do not have a Spotify account connected to your Facebook account. If you have a Spotify account, please log in with your Spotify credentials. If you do not have a Spotify account, sign up.

When I create an account by register

It takes more time but returns nothing

答: If you are in a region where Spotify is not supported, this often is the case, try using VPN.</p>

Title: Not be able to register on spotify tool


问:
Attach a file with that mail function. Is that possible?
I am using mailto function within anchor tag. I can write subject, cc bcc, body things with that. But I want to attach a file with that mail function. Is that possible?</p>

答:
PHPMailer github

using this library you can add attachments using mailto .have a look..this might help you


问:
How to chop ruby string having a random number
My string is - main_string = 'FA117RWD-20 ABC Program (version 10.0)'

In this string I just want to read FA117RWD-20 and in this string version is random which will be coming from somewhere, its version 10 right now it can be version 20 at some other time also the part that I want to read i.e. FA117RWD-20 will also be coming from somewhere randomly so is not of fix length, basically I want to chop everything that is coming after this string. How should I do it?

Thanks

答:
```<code>main_string = 'FA117RWD-20 ABC Program (version 10.0)'

main_string[/\S+/]
  #=> "FA117RWD-20"
</code>```

The regular expression matches one or more characters that are not whitespace.

Another way is the following1.

```<code>main_string[0..main_string.index(' ')-1]
</code>```

1 One can use three dots and write main_string[0...main_string.index(' ')], but I prefer to always use two dots.

Body:
main_string = 'FA117RWD-20 ABC Program (version 10.0)'

main_string[/\S+/]
  #=> "FA117RWD-20"

The regular expression matches one or more characters that are not whitespace.

Another way is the following1.

main_string[0..main_string.index(' ')-1]

1 One can use three dots and write main_string[0...main_string.index(' ')], but I prefer to always use two dots.


问:
Error while iterating with *ngFor in angular2
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

```<code>return this.http.post(this.url,params)
        .map(res => res.json())
</code>```

Assigning response to travelGuides

```<code>.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}
</code>```

JSON

```<code>{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}
</code>```

here is *ngFor im trying

```<code> <div *ngFor="let travelguide of travelGuides">
   {{travelguide.TravelGuide.Category}}
 </div>
</code>```

but getting this

```<code>Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

also tried

```<code> <div *ngFor="let travelguide of travelGuides.TravelGuide">
   {{travelguide.Category}}
 </div>
</code>```

for this getting error

```<code>Cannot read property 'TravelGuide' of undefined
</code>```

答:
If your component model looks something like this:

```<code>this.responseData = {
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      { somedata }, { somedata }, ...
    ]
  }
}
</code>```

Your markup for *ngFor would look like:

```<code><div *ngFor="let travelguide of responseData.resultData.TravelGuide">
  {{ travelguide.Category }}
</div>
</code>```

Body:
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

return this.http.post(this.url,params)
        .map(res => res.json())

Assigning response to travelGuides

.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}

JSON

{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}

here is *ngFor im trying

   {{travelguide.TravelGuide.Category}}

but getting this

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

also tried

   {{travelguide.Category}}

for this getting error

Cannot read property 'TravelGuide' of undefined

Body:
If your component model looks something like this:

this.responseData = {
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      { somedata }, { somedata }, ...
    ]
  }
}

Your markup for *ngFor would look like:

<div *ngFor="let travelguide of responseData.resultData.TravelGuide">
  {{ travelguide.Category }}
</div>