问:
Magento: Getting a shipment collection containing only shipments that contain a comment that contains a certain piece of text
I need to query for a collection of order shipments (Mage_Sales_Model_Mysql4_Order_Shipment_Collection). I only want to see the order shipment on which a comment has been written that matches a certain piece of text.

In non-EAV SQL, it would look something like this:

```<code>SELECT shipments.id
FROM shipments
JOIN comments ON (
    shipments.id = comments.shipment_id
    AND comments.content IN('Possible comment', 'Another possible comment')
    )
GROUP BY shipments.id
</code>```

Obviously I want to use Magento's native model methods to accomplish it:

```<code>$shipments = Mage::getResourceModel('sales/order_shipment_collection')
    ->addAttributeToSelect('*')
    // ??
    // ??
    ->load();
</code>```

Is this possible?

答:
To keep things neat I would put the following inside my own resource model which extends Mage_Sales_Model_Mysql4_Order_Shipment_Collection.

```<code>public function addCommentsToFilter($comments = array())
{
    return $this->join('sales/shipment_comment', 'main_table.entity_id=parent_id', 'comment')
        ->addFieldToFilter('comment', array('in'=>$comments));
}
</code>```

Then call it with:

```<code>$shipments = Mage::getResourceModel('mymodule/my_custom_collection')
    ->addAttributeToSelect('*')
    ->addCommentsToFilter(array('Possible comment', 'Another possible comment'));
</code>```

Body:
I need to query for a collection of order shipments (Mage_Sales_Model_Mysql4_Order_Shipment_Collection). I only want to see the order shipment on which a comment has been written that matches a certain piece of text.

In non-EAV SQL, it would look something like this:

SELECT shipments.id
FROM shipments
JOIN comments ON (
    shipments.id = comments.shipment_id
    AND comments.content IN('Possible comment', 'Another possible comment')
    )
GROUP BY shipments.id

Obviously I want to use Magento's native model methods to accomplish it:

$shipments = Mage::getResourceModel('sales/order_shipment_collection')
    ->addAttributeToSelect('*')
    // ??
    // ??
    ->load();

Is this possible?

Body:
To keep things neat I would put the following inside my own resource model which extends Mage_Sales_Model_Mysql4_Order_Shipment_Collection.

public function addCommentsToFilter($comments = array())
{
    return $this->join('sales/shipment_comment', 'main_table.entity_id=parent_id', 'comment')
        ->addFieldToFilter('comment', array('in'=>$comments));
}

Then call it with:

$shipments = Mage::getResourceModel('mymodule/my_custom_collection')
    ->addAttributeToSelect('*')
    ->addCommentsToFilter(array('Possible comment', 'Another possible comment'));


来源: stackexchange

问:
Is there a way to specify in Java docs that a method should be called from a non-UI thread
I was writing a set of functions for accessing/writing data to the SQLite database in my android application. Since I need to use getWritableDatabase() to get the database instance and this needs to be called in a non-UI thread, I was wondering if there a clean way to specify the same warning in the java docs of these functions?

Also, I needed one more clarification about getting handle over the database instance using getWritableDatabase(). I should call this wherever I need to write things into database right? Or can I call this once at the application level and use the same handle to access db at different places in the app?

答:
Rather than just leaving a warning in the javadoc, you might add validation, i.e. detect if you're on the UI thread (see How to check if current thread is not main thread), then throw an exception.

Document that exception.

ContentLicense: CC BY-SA 3.0


问:
Cannot insert values in database tables
I can make connection in database, I can make tables but I cannot insert any values in that table,
my code is:

```<code><?php
if (!file_exists('config.php')) {
    header('Location: install.php?page=introduction');
}
error_reporting(E_ALL);
ini_set('display_errors', '1');
echo enqueue_style('install', GET_URI_DIRECTORY . '/includes/css/install.css', '1.0');
echo enqueue_style('bootstrap', GET_URI_DIRECTORY . '/includes/css/bootstrap.min.css', '3.3.7');
echo enqueue_style('merriwheather-font', GET_URI_DIRECTORY . '/includes/css/font/merriwheather.css');
?>
<div class="container install-container">
    <div class="panel-group">
        <div class="panel panel-primary">
            <div class="panel-heading">CONFIGURATION</div>
            <div class="panel-body">
                Here you need to submit some information related to your login and site
                <form method="post" class="form-horizontal">
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="fname">First Name</label>
                        <div class="col-sm-10">
                            <input type="text" name="fname" class="form-control" id="fname" placeholder="First Name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="lname">Last Name</label>
                        <div class="col-sm-10">
                            <input type="text" name="lname" class="form-control" id="lname" placeholder="Last Name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="uname">User Name</label>
                        <div class="col-sm-10">
                            <input type="text" name="uname" class="form-control" id="uname" placeholder="User Name for login">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="pwd">Password</label>
                        <div class="col-sm-10">
                            <input type="text" name="pwd" class="form-control" id="pwd" placeholder="Password for login">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="sname">Site Name</label>
                        <div class="col-sm-10">
                            <input type="text" name="sname" class="form-control" id="sname" placeholder="Site Name">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                    <b>Note:-</b> <small>This will create your first admin account</small>
                </form>
            </div>
        </div>
    </div>
</div>
<?php

if (isset($_POST['fname'])) {
    $firstname = $_POST['fname'];
}
if (isset($_POST['lname'])) {
    $lastname = $_POST['lname'];
}
if (isset($_POST['uname'])) {
    $username = $_POST['uname'];
}
if (isset($_POST['pwd'])) {
    $password = password_hash($_POST['pwd'], PASSWORD_DEFAULT);
}
$capability = 'admin';
if (isset($_POST['sname'])) {
    $sitename = $_POST['sname'];
}

if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['uname']) && isset($_POST['pwd']) && isset($_POST['sname'])) {
    if (execute_table_making_sql() === true) {

        function configure_admin_login() {
            global $dbconn, $table_prefix, $firstname, $lastname, $username, $password, $capability;

            $firstname = mysqli_real_escape_string($firstname);
            $lastname = mysqli_real_escape_string($lastname);
            $username = mysqli_real_escape_string($username);
            $password = mysqli_real_escape_string($password);
            $capability = mysqli_real_escape_string($capability);

            $query = "INSERT INTO '{$table_prefix}'users (`FirstName`, `LastName`, `Capability`, `UserName`, `Password`) VALUES ('{$firstname}', '{$lastname}', '{$capability}', '{$username}', '{$password}')";

            if ($dbconn->query($query) === true) {
                return true;
            }
            $dbconn->error;
        }

        configure_admin_login();
    }
}
echo enqueue_script('bootstrap', GET_URI_DIRECTORY . '/includes/js/bootstrap.min.js', '3.3.7');
echo enqueue_script('jquery', GET_URI_DIRECTORY . '/includes/js/jquery-3.1.1.min.js', '3.1.1');
echo enqueue_script('smoothscroll', GET_URI_DIRECTORY . '/includes/js/smoothscroll.js', '1.2.1');
</code>```

and the code for making table is:

```<code>if (file_exists('config.php')) {
    $dbconn = database::dbconn($host, $username, $password, $database);
    if ($dbconn !== false) {
        function execute_table_making_sql() {
            global $dbconn, $table_prefix;
            $sql = 'CREATE TABLE '.$table_prefix.'users (
                    FirstName varchar(50) NOT NULL,
                    LastName varchar(50) NOT NULL,
                    Capability varchar(20) DEFAULT "member" NOT NULL,
                    UserName varchar(75) NOT NULL,
                    Password varchar(100) NOT NULL
                    )';
            if($dbconn->query($sql) === true) {
                return true;
            }
        }
    }
}

class database {

    static function dbconn($host, $user, $pass, $db) {
        $connection = new mysqli($host, $user, $pass, $db);

        if ($connection->connect_error) {
            echo "Connection failed: " . $connection->connect_error;
            return false;
        }
        return $connection;
    }
}
</code>```

I can make tables here so my db connection is true but I cannot insert any values in my tables. What is wrong with my code please tell. Help me to debug this code. Thanks in advance!

Note: Some of constant made by me they are not error, It is successfully checked before usage

答:
your problem is you create table in every time thats reason is not return true. use this.

page top.

```<code><?php

error_reporting(E_ALL);
if (file_exists('config.php')) {
    $dbconn = database::dbconn($host, $username, $password, $database);
    if ($dbconn !== false) {
        function execute_table_making_sql() {

            global $dbconn, $table_prefix;
            $sql = 'CREATE TABLE '.$table_prefix.'users (
                    FirstName varchar(50) NOT NULL,
                    LastName varchar(50) NOT NULL,
                    Capability varchar(20) DEFAULT "member" NOT NULL,
                    UserName varchar(75) NOT NULL,
                    Password varchar(100) NOT NULL
                    )';
            if(mysqli_num_rows($dbconn->query("SHOW TABLES LIKE '".$table_prefix."users'")) !=1) {
                $dbconn->query($sql);
            }
            return true;
        }
    }
}

class database {

    static function dbconn($host, $user, $pass, $db) {
        $connection = new mysqli($host, $user, $pass, $db);

        if ($connection->connect_error) {
            echo "Connection failed: " . $connection->connect_error;
            return false;
        }
        return $connection;
    }
}

?>
</code>```

in this code only update mysqli_real_escape_string because it except two parameter.

```<code>        if (isset($_POST['fname'])) {
            $firstname = $_POST['fname'];
        }
        if (isset($_POST['lname'])) {
            $lastname = $_POST['lname'];
        }
        if (isset($_POST['uname'])) {
            $username = $_POST['uname'];
        }
        if (isset($_POST['pwd'])) {
            $password = password_hash($_POST['pwd'], PASSWORD_DEFAULT);
        }
        $capability = 'admin';
        if (isset($_POST['sname'])) {
            $sitename = $_POST['sname'];
        }

        if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['uname']) && isset($_POST['pwd']) && isset($_POST['sname'])) {

            if (execute_table_making_sql() === true) {

                function configure_admin_login() {
                    global $dbconn, $table_prefix, $firstname, $lastname, $username, $password, $capability;
                    $firstname = mysqli_real_escape_string($dbconn, $firstname);
                    $lastname = mysqli_real_escape_string($dbconn, $lastname);
                    $username = mysqli_real_escape_string($dbconn, $username);
                    $password = mysqli_real_escape_string($dbconn, $password);
                    $capability = mysqli_real_escape_string($dbconn, $capability);

                    $query = "INSERT INTO users (`FirstName`, `LastName`, `Capability`, `UserName`, `Password`) VALUES ('{$firstname}', '{$lastname}', '{$capability}', '{$username}', '{$password}')";

                    if ($dbconn->query($query) === true) {
                        return true;
                    }
                    $dbconn->error;
                }

                configure_admin_login();
            }
        }
</code>```

Title: Cannot insert values in database tables

Body:
I can make connection in database, I can make tables but I cannot insert any values in that table,
my code is:

<?php
if (!file_exists('config.php')) {
    header('Location: install.php?page=introduction');
}
error_reporting(E_ALL);
ini_set('display_errors', '1');
echo enqueue_style('install', GET_URI_DIRECTORY . '/includes/css/install.css', '1.0');
echo enqueue_style('bootstrap', GET_URI_DIRECTORY . '/includes/css/bootstrap.min.css', '3.3.7');
echo enqueue_style('merriwheather-font', GET_URI_DIRECTORY . '/includes/css/font/merriwheather.css');
?>

CONFIGURATION

                Here you need to submit some information related to your login and site
                <form method="post" class="form-horizontal">

                        First Name

                            <input type="text" name="fname" class="form-control" id="fname" placeholder="First Name">

                        Last Name

                            <input type="text" name="lname" class="form-control" id="lname" placeholder="Last Name">

                        User Name

                            <input type="text" name="uname" class="form-control" id="uname" placeholder="User Name for login">

                        Password

                            <input type="text" name="pwd" class="form-control" id="pwd" placeholder="Password for login">

                        Site Name

                            <input type="text" name="sname" class="form-control" id="sname" placeholder="Site Name">

                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                    Note:- This will create your first admin account
                </form>

<?php

if (isset($_POST['fname'])) {
    $firstname = $_POST['fname'];
}
if (isset($_POST['lname'])) {
    $lastname = $_POST['lname'];
}
if (isset($_POST['uname'])) {
    $username = $_POST['uname'];
}
if (isset($_POST['pwd'])) {
    $password = password_hash($_POST['pwd'], PASSWORD_DEFAULT);
}
$capability = 'admin';
if (isset($_POST['sname'])) {
    $sitename = $_POST['sname'];
}

if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['uname']) && isset($_POST['pwd']) && isset($_POST['sname'])) {
    if (execute_table_making_sql() === true) {

        function configure_admin_login() {
            global $dbconn, $table_prefix, $firstname, $lastname, $username, $password, $capability;

            $firstname = mysqli_real_escape_string($firstname);
            $lastname = mysqli_real_escape_string($lastname);
            $username = mysqli_real_escape_string($username);
            $password = mysqli_real_escape_string($password);
            $capability = mysqli_real_escape_string($capability);

            $query = "INSERT INTO '{$table_prefix}'users (`FirstName`, `LastName`, `Capability`, `UserName`, `Password`) VALUES ('{$firstname}', '{$lastname}', '{$capability}', '{$username}', '{$password}')";

            if ($dbconn->query($query) === true) {
                return true;
            }
            $dbconn->error;
        }

        configure_admin_login();
    }
}
echo enqueue_script('bootstrap', GET_URI_DIRECTORY . '/includes/js/bootstrap.min.js', '3.3.7');
echo enqueue_script('jquery', GET_URI_DIRECTORY . '/includes/js/jquery-3.1.1.min.js', '3.1.1');
echo enqueue_script('smoothscroll', GET_URI_DIRECTORY . '/includes/js/smoothscroll.js', '1.2.1');

and the code for making table is:

if (file_exists('config.php')) {
    $dbconn = database::dbconn($host, $username, $password, $database);
    if ($dbconn !== false) {
        function execute_table_making_sql() {
            global $dbconn, $table_prefix;
            $sql = 'CREATE TABLE '.$table_prefix.'users (
                    FirstName varchar(50) NOT NULL,
                    LastName varchar(50) NOT NULL,
                    Capability varchar(20) DEFAULT "member" NOT NULL,
                    UserName varchar(75) NOT NULL,
                    Password varchar(100) NOT NULL
                    )';
            if($dbconn->query($sql) === true) {
                return true;
            }
        }
    }
}

class database {

    static function dbconn($host, $user, $pass, $db) {
        $connection = new mysqli($host, $user, $pass, $db);

        if ($connection->connect_error) {
            echo "Connection failed: " . $connection->connect_error;
            return false;
        }
        return $connection;
    }
}

I can make tables here so my db connection is true but I cannot insert any values in my tables. What is wrong with my code please tell. Help me to debug this code. Thanks in advance!

Note: Some of constant made by me they are not error, It is successfully checked before usage

Body:
your problem is you create table in every time thats reason is not return true. use this.

page top.

<?php

error_reporting(E_ALL);
if (file_exists('config.php')) {
    $dbconn = database::dbconn($host, $username, $password, $database);
    if ($dbconn !== false) {
        function execute_table_making_sql() {

            global $dbconn, $table_prefix;
            $sql = 'CREATE TABLE '.$table_prefix.'users (
                    FirstName varchar(50) NOT NULL,
                    LastName varchar(50) NOT NULL,
                    Capability varchar(20) DEFAULT "member" NOT NULL,
                    UserName varchar(75) NOT NULL,
                    Password varchar(100) NOT NULL
                    )';
            if(mysqli_num_rows($dbconn->query("SHOW TABLES LIKE '".$table_prefix."users'")) !=1) {
                $dbconn->query($sql);
            }
            return true;
        }
    }
}

class database {

    static function dbconn($host, $user, $pass, $db) {
        $connection = new mysqli($host, $user, $pass, $db);

        if ($connection->connect_error) {
            echo "Connection failed: " . $connection->connect_error;
            return false;
        }
        return $connection;
    }
}

?>

in this code only update mysqli_real_escape_string because it except two parameter.

        if (isset($_POST['fname'])) {
            $firstname = $_POST['fname'];
        }
        if (isset($_POST['lname'])) {
            $lastname = $_POST['lname'];
        }
        if (isset($_POST['uname'])) {
            $username = $_POST['uname'];
        }
        if (isset($_POST['pwd'])) {
            $password = password_hash($_POST['pwd'], PASSWORD_DEFAULT);
        }
        $capability = 'admin';
        if (isset($_POST['sname'])) {
            $sitename = $_POST['sname'];
        }

        if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['uname']) && isset($_POST['pwd']) && isset($_POST['sname'])) {

            if (execute_table_making_sql() === true) {

                function configure_admin_login() {
                    global $dbconn, $table_prefix, $firstname, $lastname, $username, $password, $capability;
                    $firstname = mysqli_real_escape_string($dbconn, $firstname);
                    $lastname = mysqli_real_escape_string($dbconn, $lastname);
                    $username = mysqli_real_escape_string($dbconn, $username);
                    $password = mysqli_real_escape_string($dbconn, $password);
                    $capability = mysqli_real_escape_string($dbconn, $capability);

                    $query = "INSERT INTO users (`FirstName`, `LastName`, `Capability`, `UserName`, `Password`) VALUES ('{$firstname}', '{$lastname}', '{$capability}', '{$username}', '{$password}')";

                    if ($dbconn->query($query) === true) {
                        return true;
                    }
                    $dbconn->error;
                }

                configure_admin_login();
            }
        }


问:
Azure Graph API Nested Group Membership
I need to query a user's nested group membership. memberOf only give direct group membership. When I try getMemberGroups, getMemberObjects, checkMemberGroups, etc. using version 1.5 or 1.6, I'm getting this:

```<code>{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "Method Not Allowed"
        }
    }
}
</code>```

Any ideas on how to fix this?

答:
You might be making a GET request. According to documentation, you need to make a POST request for getMemberGroups.

URL:

```<code>https://graph.windows.net/domain.com/users/first.last@domain.com/getMemberGroups?api-version=1.6
</code>```

Request body:

```<code>{
  "securityEnabledOnly": true
}
</code>```

Here the parameter defines if you want only security groups back, or if it should return Office 365 groups too.

ContentLicense: CC BY-SA 4.0

Title: Azure Graph API Nested Group Membership

Body:
I need to query a user's nested group membership. memberOf only give direct group membership. When I try getMemberGroups, getMemberObjects, checkMemberGroups, etc. using version 1.5 or 1.6, I'm getting this:

{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "Method Not Allowed"
        }
    }
}

Any ideas on how to fix this?

Body:
You might be making a GET request. According to documentation, you need to make a POST request for getMemberGroups.

URL:

https://graph.windows.net/domain.com/users/first.last@domain.com/getMemberGroups?api-version=1.6

Request body:

{
  "securityEnabledOnly": true
}

Here the parameter defines if you want only security groups back, or if it should return Office 365 groups too.


问:
How to load string.xml for indian languages in android?
I am trying to load strings.xml files for following Indian languages:

Oriya (values-or)

Bengali (values-bn)

Punjabi (values-pa)

Gujarati (values-gu)

Marathi (values-mr)

Malayalam (values-ml)

Telugu (values-te)

Tamil (values-ta)

Kannada (values-kn)

and tried with values-or-rIN,..etc as well. and using following code to load locale:

```<code>public void changeLang(String lang) {
        Configuration config = getBaseContext().getResources().getConfiguration();
        if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {

            SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
            ed.putString(getString(R.string.locale_lang), lang);
            ed.commit();

            locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration conf = new Configuration(config);
            conf.locale = locale;
            getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(this.getString(R.string.locale_lang), lang);
            editor.commit();
        }
    }
</code>```

Above code is working for all international languages. but not for above-mentioned languages. I saw many answers, as per them we need to load fonts ttf files of the corresponding language. But I don't want to load fonts (TypeFace). I want to load strings.xml.

Could anyone suggest how to load strings.xml of Indian languages? Is it possible? or Should I go for fonts ttf for above-mentioned languages??

答:
I had done this following way:

```<code>    String lang = "ml";//for malyalam language

    if(lang.equalsIgnoreCase(getResources().getString(R.string.text_item_ml))) {
              lang = Constants.LANGUAGE_CODE_MALAYALAM;
              country = Constants.COUNTRY_CODE_INDIA;
         }

    Locale locale;
    if (country == null) {
       locale = new Locale(lang);
      } else {
              locale = new Locale(lang, country);
             }
      Locale.setDefault(locale);
      Configuration config = new Configuration();
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
onConfigurationChanged(config);
</code>```

And values folder name should be:

values-ml-rIN

values-gu-rIN

If your phone not supporting particular character then only you need font other wise no need custom font, I made application which is supporting 12 indian local language without any custom font.

Check that your phone supported particular lang or not using below method

```<code>public static boolean isSupported(Context context, String text) {
        final int WIDTH_PX = 200;
        final int HEIGHT_PX = 80;

        int w = WIDTH_PX, h = HEIGHT_PX;
        Resources resources = context.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
        Bitmap orig = bitmap.copy(conf, false);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.rgb(0, 0, 0));
        paint.setTextSize((int) (14 * scale));

        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int x = (bitmap.getWidth() - bounds.width()) / 2;
        int y = (bitmap.getHeight() + bounds.height()) / 2;

        canvas.drawText(text, x, y, paint);
        boolean res = !orig.sameAs(bitmap);
        orig.recycle();
        bitmap.recycle();
        return res;
    }
</code>```

Hope It will help you !

Body:
I am trying to load strings.xml files for following Indian languages:

Oriya (values-or)

Bengali (values-bn)

Punjabi (values-pa)

Gujarati (values-gu)

Marathi (values-mr)

Malayalam (values-ml)

Telugu (values-te)

Tamil (values-ta)

Kannada (values-kn)

and tried with values-or-rIN,..etc as well. and using following code to load locale:

public void changeLang(String lang) {
        Configuration config = getBaseContext().getResources().getConfiguration();
        if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {

            SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
            ed.putString(getString(R.string.locale_lang), lang);
            ed.commit();

            locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration conf = new Configuration(config);
            conf.locale = locale;
            getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(this.getString(R.string.locale_lang), lang);
            editor.commit();
        }
    }

Above code is working for all international languages. but not for above-mentioned languages. I saw many answers, as per them we need to load fonts ttf files of the corresponding language. But I don't want to load fonts (TypeFace). I want to load strings.xml.

Could anyone suggest how to load strings.xml of Indian languages? Is it possible? or Should I go for fonts ttf for above-mentioned languages??

Body:
I had done this following way:

    String lang = "ml";//for malyalam language

    if(lang.equalsIgnoreCase(getResources().getString(R.string.text_item_ml))) {
              lang = Constants.LANGUAGE_CODE_MALAYALAM;
              country = Constants.COUNTRY_CODE_INDIA;
         }

    Locale locale;
    if (country == null) {
       locale = new Locale(lang);
      } else {
              locale = new Locale(lang, country);
             }
      Locale.setDefault(locale);
      Configuration config = new Configuration();
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
onConfigurationChanged(config);

And values folder name should be:

values-ml-rIN

values-gu-rIN

If your phone not supporting particular character then only you need font other wise no need custom font, I made application which is supporting 12 indian local language without any custom font.

Check that your phone supported particular lang or not using below method

public static boolean isSupported(Context context, String text) {
        final int WIDTH_PX = 200;
        final int HEIGHT_PX = 80;

        int w = WIDTH_PX, h = HEIGHT_PX;
        Resources resources = context.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
        Bitmap orig = bitmap.copy(conf, false);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.rgb(0, 0, 0));
        paint.setTextSize((int) (14 * scale));

        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int x = (bitmap.getWidth() - bounds.width()) / 2;
        int y = (bitmap.getHeight() + bounds.height()) / 2;

        canvas.drawText(text, x, y, paint);
        boolean res = !orig.sameAs(bitmap);
        orig.recycle();
        bitmap.recycle();
        return res;
    }

Hope It will help you !


问:
x-.y And what about intersection?
x-.y includes all items of x except for those that are cells of y

But what if I want to get all items that are cells of x and of y?

I can achieve this by

```<code>x -.^:2 y
</code>```

But it require running expensive operation twice.
Is there a better solution?

答:
Doing -. twice is the classic way of implementing intersection in J.

The inefficiency is minor (a constant factor - and, in general, you should not concern yourself with efficiency issues in J unless they exceed a factor of 2 - when you have resource problems you're generally going to want to focus on the factor of 1000 or greater issues).

Put differently, if ([-.-.) or -.^:2 is too slow for you then -. would also be too slow for you. (This can happen on extremely large data sets where the underlying implementation has been inefficient. Recent versions of J have had some work done, to correct this issue.)

Disappointing, perhaps, but practical.

Title: x-.y And what about intersection?

Body:
x-.y includes all items of x except for those that are cells of y

But what if I want to get all items that are cells of x and of y?

I can achieve this by

x -.^:2 y

But it require running expensive operation twice.
Is there a better solution?


问:
How to display birth year in oracle?
The question is display the details of customer whose birth year is 1980 want to display like this

```<code>Name | Surname | mob_no     |  city  | birth_year
-------------------------------------------------
Jack | Jones   | 9892xxxxxx | Mumbai | 1980
</code>```

EDIT:

data:

```<code>CUST_NO  FNAME    BIRTH_DATE    CITY           MOB_NO   DEPT_NAME    SALARY
------- -------- ------------- ----------  ----------   ------------ -------
   4583  Maitri   15-Aug-1997   Singapore  982xxxxxxx    Doctor       300000
   9087  Sajal    17-mar-1992   Nasik       991xxxxxx    Banker       180000
   6789  Yash     23-Feb-1980   Mumbai      123xxxxxx    Analyst      150000
   2346  Kriti    23-Feb-1980   Mumbai     99xxxxxxxx    Programmer    20000
</code>```

In birth_date column there is birth year I want to display birth year and the details of employees.

This is what I have tried

```<code>select *
from table name
where(birth_date) in (select birth_date
                      from table name
                      group by birth_date having count(birth_date)>1
                      )
order by birth_date;
</code>```

答:
If I understand your question, this is what you need:

```<code>select CUST_NO,
       FNAME,
       extract(year from BIRTH_DATE) AS BIRTH_YEAR,
       CITY,
       MOB_NO,
       DEPT_NAME,
       SALARY
from CUSTOMER
WHERE ...
</code>```

Another way could be

```<code>to_char(BIRTH_DATE,'YYYY') AS BIRTH_YEAR
</code>```

The first one gives a numeric value, while the second one gives the year as a string.

Title: How to display birth year in oracle?

Body:
The question is display the details of customer whose birth year is 1980 want to display like this

Name | Surname | mob_no     |  city  | birth_year
-------------------------------------------------
Jack | Jones   | 9892xxxxxx | Mumbai | 1980

EDIT:

data:

CUST_NO  FNAME    BIRTH_DATE    CITY           MOB_NO   DEPT_NAME    SALARY
------- -------- ------------- ----------  ----------   ------------ -------
   4583  Maitri   15-Aug-1997   Singapore  982xxxxxxx    Doctor       300000
   9087  Sajal    17-mar-1992   Nasik       991xxxxxx    Banker       180000
   6789  Yash     23-Feb-1980   Mumbai      123xxxxxx    Analyst      150000
   2346  Kriti    23-Feb-1980   Mumbai     99xxxxxxxx    Programmer    20000

In birth_date column there is birth year I want to display birth year and the details of employees.

This is what I have tried

select *
from table name
where(birth_date) in (select birth_date
                      from table name
                      group by birth_date having count(birth_date)>1
                      )
order by birth_date;

Body:
If I understand your question, this is what you need:

select CUST_NO,
       FNAME,
       extract(year from BIRTH_DATE) AS BIRTH_YEAR,
       CITY,
       MOB_NO,
       DEPT_NAME,
       SALARY
from CUSTOMER
WHERE ...

Another way could be

to_char(BIRTH_DATE,'YYYY') AS BIRTH_YEAR

The first one gives a numeric value, while the second one gives the year as a string.


问:
Doctrine Query Builder LOWER not working
Somehow doctrine is not allowing me to compare two lowerstring values: that of a variable and the first name of a user.

```<code>    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb
        ->select('d')
        ->from('MyBundle:User', 'd')
        ->where('LOWER(d.firstName) LIKE :fName')
        ->setParameter('fName', strtolower('%'.$fName.'%'));

    $result = $qb->getQuery()->execute();
</code>```

only when $fName has an uppercase string (i.e. 'Rob'), it will return results like 'Robert' and 'Robby'. But what I want is that even when $fName is spelled lowercase ('rob'), these results should come up. It seems that the d.firstNames are not lowered. Why is this the case?

答:
you can use :

```<code>mb_strtolower()
</code>```

http://php.net/manual/en/function.mb-strtolower.php

Body:
Somehow doctrine is not allowing me to compare two lowerstring values: that of a variable and the first name of a user.

    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb
        ->select('d')
        ->from('MyBundle:User', 'd')
        ->where('LOWER(d.firstName) LIKE :fName')
        ->setParameter('fName', strtolower('%'.$fName.'%'));

    $result = $qb->getQuery()->execute();

only when $fName has an uppercase string (i.e. 'Rob'), it will return results like 'Robert' and 'Robby'. But what I want is that even when $fName is spelled lowercase ('rob'), these results should come up. It seems that the d.firstNames are not lowered. Why is this the case?

Body:
you can use :

mb_strtolower()

http://php.net/manual/en/function.mb-strtolower.php


问:
SQL_BIG_SELECTS error
UPDATE

now I can make it work by remove ORDER BY... not sure that's the right thing to do but have to.

First of all,This is all fields(columns) in all table I want to join in the database

and the field in highlighted is the field i want to select.

So, I wrote sql syntax to join all table like this

```<code>SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       date_format(section_data_content_p.start_date,'%Y-%m-%d') as start_date,
       date_format(section_data_content_p.end_date,'%Y-%m-%d') as end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM
(
    (country_policies
     INNER JOIN section_data_content_p
         ON country_policies.policyid = section_data_content_p.policy_id AND
            country_policies.countryid = section_data_content_p.country_id
    )
    INNER JOIN section_data_structure
        ON section_data_content_p.data_structure_id = section_data_structure.id
    INNER JOIN sections_content
        ON section_data_content_p.state_id = sections_content.statecode
)
order by section_data_content_p.dropname;
</code>```

then I got this error

ER_TOO_BIG_SELECT: The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay

So I tried to add SET SQL_BIG_SELECTS= 1 ; to the top like this

```<code>SET SQL_BIG_SELECTS= 1 ;
SELECT country_policies.policyname, country_policies.countryname, section_data_structure.data_name, section_data_content_p.dropname, section_data_content_p.comment, date_format(section_data_content_p.start_date,'%Y-%m-%d') as start_date, date_format(section_data_content_p.end_date,'%Y-%m-%d') as end_date,section_data_content_p.policy_id,section_data_content_p.country_id,sections_content.section_id,sections_content.statecode
FROM  ((country_policies
INNER JOIN section_data_content_p ON country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id)
INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode) order by section_data_content_p.dropname;
</code>```

then I got an error again

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET SQL_BIG_SELECTS= 1
  SELECT country_policies.policyname, country_policies.co' at line 1

also tried SET SESSION/ SET OPTION but all not work
and I still can't solve this. mysql version is 5.6.32

anyone can help? thanks

答:
I have tidied up some of the bracket usage in your two code samples.  The first is now...

```<code>SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       DATE_FORMAT( section_data_content_p.start_date,
                    '%Y-%m-%d' ) AS start_date,
       DATE_FORMAT( section_data_content_p.end_date,
                    '%Y-%m-%d' ) AS end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM country_policies
     INNER JOIN section_data_content_p ON ( country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id )
     INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
     INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode
ORDER BY section_data_content_p.dropname;
</code>```

I have also made the setting of SQL_BIG_SELECT a session variable, as per MySQL - SQL_BIG_SELECTS in the altered second piece of code, which is as follows...

```<code>SET SESSION SQL_BIG_SELECTS = 1;
SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       DATE_FORMAT( section_data_content_p.start_date,
                    '%Y-%m-%d' ) AS start_date,
       DATE_FORMAT( section_data_content_p.end_date,
                    '%Y-%m-%d' ) AS end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM country_policies
     INNER JOIN section_data_content_p ON ( country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id )
     INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
     INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode
ORDER BY section_data_content_p.dropname;
</code>```

Note : I have also altered the layout to a style that I find much easier to debug in.

If you have any questions or comments, then please feel free to post a Comment accordingly.

Title: SQL_BIG_SELECTS error

Body:
UPDATE

now I can make it work by remove ORDER BY... not sure that's the right thing to do but have to.

First of all,This is all fields(columns) in all table I want to join in the database

and the field in highlighted is the field i want to select.

So, I wrote sql syntax to join all table like this

SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       date_format(section_data_content_p.start_date,'%Y-%m-%d') as start_date,
       date_format(section_data_content_p.end_date,'%Y-%m-%d') as end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM
(
    (country_policies
     INNER JOIN section_data_content_p
         ON country_policies.policyid = section_data_content_p.policy_id AND
            country_policies.countryid = section_data_content_p.country_id
    )
    INNER JOIN section_data_structure
        ON section_data_content_p.data_structure_id = section_data_structure.id
    INNER JOIN sections_content
        ON section_data_content_p.state_id = sections_content.statecode
)
order by section_data_content_p.dropname;

then I got this error

ER_TOO_BIG_SELECT: The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay

So I tried to add SET SQL_BIG_SELECTS= 1 ; to the top like this

SET SQL_BIG_SELECTS= 1 ;
SELECT country_policies.policyname, country_policies.countryname, section_data_structure.data_name, section_data_content_p.dropname, section_data_content_p.comment, date_format(section_data_content_p.start_date,'%Y-%m-%d') as start_date, date_format(section_data_content_p.end_date,'%Y-%m-%d') as end_date,section_data_content_p.policy_id,section_data_content_p.country_id,sections_content.section_id,sections_content.statecode
FROM  ((country_policies
INNER JOIN section_data_content_p ON country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id)
INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode) order by section_data_content_p.dropname;

then I got an error again

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET SQL_BIG_SELECTS= 1
  SELECT country_policies.policyname, country_policies.co' at line 1

also tried SET SESSION/ SET OPTION but all not work
and I still can't solve this. mysql version is 5.6.32

anyone can help? thanks

Body:
I have tidied up some of the bracket usage in your two code samples.  The first is now...

SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       DATE_FORMAT( section_data_content_p.start_date,
                    '%Y-%m-%d' ) AS start_date,
       DATE_FORMAT( section_data_content_p.end_date,
                    '%Y-%m-%d' ) AS end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM country_policies
     INNER JOIN section_data_content_p ON ( country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id )
     INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
     INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode
ORDER BY section_data_content_p.dropname;

I have also made the setting of SQL_BIG_SELECT a session variable, as per MySQL - SQL_BIG_SELECTS in the altered second piece of code, which is as follows...

SET SESSION SQL_BIG_SELECTS = 1;
SELECT country_policies.policyname,
       country_policies.countryname,
       section_data_structure.data_name,
       section_data_content_p.dropname,
       section_data_content_p.comment,
       DATE_FORMAT( section_data_content_p.start_date,
                    '%Y-%m-%d' ) AS start_date,
       DATE_FORMAT( section_data_content_p.end_date,
                    '%Y-%m-%d' ) AS end_date,
       section_data_content_p.policy_id,
       section_data_content_p.country_id,
       sections_content.section_id,
       sections_content.statecode
FROM country_policies
     INNER JOIN section_data_content_p ON ( country_policies.policyid = section_data_content_p.policy_id AND country_policies.countryid = section_data_content_p.country_id )
     INNER JOIN section_data_structure ON section_data_content_p.data_structure_id = section_data_structure.id
     INNER JOIN sections_content ON section_data_content_p.state_id = sections_content.statecode
ORDER BY section_data_content_p.dropname;

Note : I have also altered the layout to a style that I find much easier to debug in.

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
Print output not showing the correct format
I have written the python code as below:

```<code>magicNumber = 25

for n in range(100):
    if n is magicNumber:
        print(n, " is the magic number")
        break
    else:
        print(n)
</code>```

The last line of output is showing in the format as below:

```<code>(25, ' is the magic number')
</code>```

Please let me know what can i do to have the last line of the output as:

```<code>25 is the magic number
</code>```

答:
There's many ways you can accomplish this, since you're using python 2, there isn't a default print function. So you will have to import it, one way will be to add this on the top of your code.

```<code>from __future__ import print_function
</code>```

Other ways include using string formatting such as:

```<code>print "%s is the magic number" % n
</code>```

And

```<code>print "{0} is the magic number".format(n)
</code>```

Or you can just easily remove the brackets and it will all be the same.

```<code>print n, "is the magic number"
</code>```

Body:
I have written the python code as below:

magicNumber = 25

for n in range(100):
    if n is magicNumber:
        print(n, " is the magic number")
        break
    else:
        print(n)

The last line of output is showing in the format as below:

(25, ' is the magic number')

Please let me know what can i do to have the last line of the output as:

25 is the magic number

Body:
There's many ways you can accomplish this, since you're using python 2, there isn't a default print function. So you will have to import it, one way will be to add this on the top of your code.

from __future__ import print_function

Other ways include using string formatting such as:

print "%s is the magic number" % n

And

print "{0} is the magic number".format(n)

Or you can just easily remove the brackets and it will all be the same.

print n, "is the magic number"


问:
What security concerns are there in sharing the SigningCertificate
I know the IdentityServerOptions.SigningCertificate is used to sign the tokens provided by IDS.  Are there any concernes if this certificate was available outside of IDS?  Is it possible to craft an access token if you have access to this certificate?

We have a product we were wondering if we should ship a premade certifcate inside the msi installer, or we need to ship the sdk (or makecert) to generate a unique one for each client.  Obviously the easiest option is to ship a pre-prepared one, just want to understand the risks.

答:
As I understand it you're going to be distributing a copy of IdentityServer with your system so you'll have lots of installations out there each with its own IdentityServer.

Basically IdentityServer needs to have access to the private key in order to sign its tokens so if you supply the same certificate+private key for all installations then in theory one installation could trust the tokens from another. Obviously the content of the tokens is also relevant but seeing as this is your system it's not so unlikely that scopes, claims, etc could make sense across installations.

If you add a malicious person into the mix then they could simply choose the contents of the token and sign it, they could even use the IdentityServer code itself to do this as it's open source.

You should look into allowing administrators to load a pfx file or configure a signing certificate that exists in a certificate store. There are various gotchas to both approaches, this blog post has some good info about problems you may encounter:

http://paulstovell.com/blog/x509certificate2

You'll also want to consider how you renew certificates, IdentityServer has good support for this, info in the docs here:

https://identityserver.github.io/Documentation/docsv2/configuration/crypto.html

Edit:

In case my initial assumption is incorrect and there will only be one IdentityServer which will be under your control and you'll only distribute the public key then that's fine! Here's a good explanation of public vs private keys and terminology:

https://security.stackexchange.com/questions/29425/difference-between-pfx-and-cert-certificates


问:
Input Hex into argv[1]
I have a program that takes input from argv[1] so I run it like

```<code>./myProgram Hello
</code>```

But I need to input hexadecimals instead of decimal/text so something like

```<code>./myProgram \x48\x65\x6c\x6c\x6f
</code>```

but the program takes that in as text instead of hexadecimals that form the word Hello.

I can't

```<code>python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram
</code>```

because the program takes the data in as argv[1]

How do I solve the problem? (I cannot modify the program)

答:
Let's assume you're writting a program as the post is tagged c.

1) command line parameter format will be like following:

```<code>./myProgram 0x55 0xAA 0xBB ...
</code>```

or even

```<code>./myProgram 55 66 AA BB ...
</code>```

2) in your program all input parameters will be available via argv array as strings. You can use sscanf with format %X to read hex values out of them and store them into unsigned integer variables. Also, in the simplest case it will look similar to:

```<code>unsigned int var;
sscanf(argv[1], "%X", &var); // will read 0x55
sscanf(argv[2], "%X", &var); // will read 0x66 and so on
</code>```

Title: Input Hex into argv[1]

Body:
I have a program that takes input from argv[1] so I run it like

./myProgram Hello

But I need to input hexadecimals instead of decimal/text so something like

./myProgram \x48\x65\x6c\x6c\x6f

but the program takes that in as text instead of hexadecimals that form the word Hello.

I can't

python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram

because the program takes the data in as argv[1]

How do I solve the problem? (I cannot modify the program)

Body:
Let's assume you're writting a program as the post is tagged c.

1) command line parameter format will be like following:

./myProgram 0x55 0xAA 0xBB ...

or even

./myProgram 55 66 AA BB ...

2) in your program all input parameters will be available via argv array as strings. You can use sscanf with format %X to read hex values out of them and store them into unsigned integer variables. Also, in the simplest case it will look similar to:

unsigned int var;
sscanf(argv[1], "%X", &var); // will read 0x55
sscanf(argv[2], "%X", &var); // will read 0x66 and so on


问:
Laravel unauthorized page when ajax send request

I'm making web based game. The game need to login first, so I use laravel auth::register and auth::login as usual, and add middleware auth to every pages except login&register page.
Then check the game status using smartupdater if ready or not.

```<code>$("section").smartupdater({
    url       : urlCheckStatus,
    data      : data,
    dataType  : 'json',
    minTimeout: 2000
}, function(response){
    var gameStatus = response.data.status;

    if(gameStatus === 'start')
    {
        gameOn();
    }
    else if(gameStatus === 'active')
    {
        pleaseWait();
    }
    else if(gameStatus === 'stop')
    {
        backToMenu();
    }
});
</code>```

Register and login function

```<code>public function register(Request $request)
{
    $name = $request->input('username');

    $user = new User;
    $user->name     = $request->input('username');
    $user->email    = $name.'@abc.com';
    $user->password = bcrypt(Carbon\Carbon::now());
    $user->grade    = $request->input('grade');
    $user->numb     = $request->input('numb');
    $user->save();

    Auth::login($user, true);

    return redirect('menu');
}
</code>```

check game status function

```<code>public function checkGameStatus()
{
    $game_id = Request::input('game_id');
    $data    = Game::find($game_id);

    return response()->json([
        'data'  => $data
    ]);
}
</code>```

But sometimes I was thrown to login page, because error 401 Unauthorized. Trying to console log like the image above.

Thanks

答:
I see you are using Javascript for authorization with Laravel, as per Laravel documentation for API Authentication with Javascript:

If you are using a different JavaScript framework, you should make
  sure it is configured to send the X-CSRF-TOKEN and X-Requested-With
  headers with every outgoing request.

Can you ensure X-CSRF-TOKEN and X-Requested-With are always present in your headers.

Body:
I'm making web based game. The game need to login first, so I use laravel auth::register and auth::login as usual, and add middleware auth to every pages except login&register page.
Then check the game status using smartupdater if ready or not.

$("section").smartupdater({
    url       : urlCheckStatus,
    data      : data,
    dataType  : 'json',
    minTimeout: 2000
}, function(response){
    var gameStatus = response.data.status;

    if(gameStatus === 'start')
    {
        gameOn();
    }
    else if(gameStatus === 'active')
    {
        pleaseWait();
    }
    else if(gameStatus === 'stop')
    {
        backToMenu();
    }
});

Register and login function

public function register(Request $request)
{
    $name = $request->input('username');

    $user = new User;
    $user->name     = $request->input('username');
    $user->email    = $name.'@abc.com';
    $user->password = bcrypt(Carbon\Carbon::now());
    $user->grade    = $request->input('grade');
    $user->numb     = $request->input('numb');
    $user->save();

    Auth::login($user, true);

    return redirect('menu');
}

check game status function

public function checkGameStatus()
{
    $game_id = Request::input('game_id');
    $data    = Game::find($game_id);

    return response()->json([
        'data'  => $data
    ]);
}

But sometimes I was thrown to login page, because error 401 Unauthorized. Trying to console log like the image above.

Thanks


问:
Objective-C UIWebView not loading website
I am trying to get a UIWebView to display google.com for now, but its not loading:

I just get a blank screen

.h

```<code>#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIWebView *webView;

@end
</code>```

.m

```<code>#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    NSURL *targetURL = [NSURL URLWithString:@"http://www.google.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [_webView loadRequest:request];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

What I did is the following to create a web view:

Created a new UIViewController scene

Added a UIWebView to it

connected the webview to .h controller

Made my scene the inital scene

Ran the app, nothing was loaded, no errors, just go straight to UIViewController with nothing in it, please help.

I tried adding the following:

```<code>[self.view addSubview:self.webView];
</code>```

That did nothing

答:
add Break point , check if NSURLRequest *request is nil ,
if nil, then do

```<code>NSString *urlString = @"http://www.yourWebAddress.com";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
</code>```

try to encode the url...hope it will works

Body:
I am trying to get a UIWebView to display google.com for now, but its not loading:

I just get a blank screen

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIWebView *webView;

@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    NSURL *targetURL = [NSURL URLWithString:@"http://www.google.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [_webView loadRequest:request];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

What I did is the following to create a web view:

Created a new UIViewController scene

Added a UIWebView to it

connected the webview to .h controller

Made my scene the inital scene

Ran the app, nothing was loaded, no errors, just go straight to UIViewController with nothing in it, please help.

I tried adding the following:

[self.view addSubview:self.webView];

That did nothing

Body:
add Break point , check if NSURLRequest *request is nil ,
if nil, then do

NSString *urlString = @"http://www.yourWebAddress.com";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];

try to encode the url...hope it will works


问:
Qml listView mirroring layout current Index
I am working with ListView component and I have trouble with currentIndex property. I want to do some action on

```<code>onCurrentIndexChanged:
</code>```

But when I use

```<code>LayoutMirroring.enabled: true
</code>```

currentIndex is not updated anymore. There is no action in onCurrentIndexChanged and currentIndex is equal to 0 all the time.
I've also tried to use

layoutDirection: Qt.RightToLeft
but problem is the same ( no currentIndex updates when listView is moved).

I've read ListView documentation and there was information, that if you use

```<code>snapMode: ListView.SnapToItem
</code>```

you also need to add

```<code>highlightRangeMode:  ListView.StrictlyEnforceRange
</code>```

in order to currentIndex is update properly. Maybe there is something similar for mirror layout?

Here is the whole code:

```<code>ListView
    {
        id: id_couplingControlView

        model: id_multiCouplingMeasurePopup.p_iCouplingsCount
        orientation: ListView.Horizontal
        snapMode: ListView.SnapToItem
        highlightRangeMode:  ListView.StrictlyEnforceRange          //To update the currentIndex as the list is moved
        preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin
        LayoutMirroring.enabled:  id_multiCouplingMeasurePopup.p_bViewRotated
        //layoutDirection: id_multiCouplingMeasurePopup.p_bViewRotated ? Qt.RightToLeft : Qt.LeftToRight

        delegate: QmlSHMultiCouplingMeasureControl
        {
            id: id_CouplingMeasureControl

            p_iIndex: index
            Component.onCompleted:
            {
                InitializeCouplingControl ( id_CouplingMeasureControl )
            }
        }

        //Need to to something here
        onCurrentIndexChanged:
        {
            console.log ( "onCurrentIndexChanged:: " + id_couplingControlView.currentIndex )
            id_multiCouplingMeasurePopup.UpdateMiniTrainCouplingList( id_couplingControlView.currentIndex );
        }
    }
</code>```

So my question is: what I need to do to have currentIndex updated while scrolling listView when using LayoutMirroring.enabled: true or layoutDirection: Qt.RightToLeft.

答:
If you had provided a Minimal, Complete and Verifyable Example we might have come down to the core of your problem.

So to answer your question: You need to do, exactly what you assumed:

Make the ListView horizontal: orientation: ListView.Horizontal

Enable mirroring: LayoutMirroring.enabled: true

Snap to Item: snapMode: ListView.SnapToItem <= Actually seems optional

enforce the currenItem to be in the view: highlightRangeMode:  ListView.StrictlyEnforceRange

This is how a MCVE could look like, that proves that it works as expected:

```<code>ListView {
    id: lv
    model: 100
    LayoutMirroring.enabled: true
    orientation: ListView.Horizontal
    width: 500
    height: 100
    spacing: 5
    snapMode: ListView.SnapToItem
    highlightRangeMode:  ListView.StrictlyEnforceRange
    onCurrentIndexChanged: console.log('Current Index changed to', currentIndex)

    delegate: Rectangle {
        width: 100
        height: 100
        color: lv.currentItem === this ? Qt.rgba(1, 0, 0, 1) : Qt.rgba(0, 0, 1, index / 200 + 0.5)
    }
}
</code>```

Body:
I am working with ListView component and I have trouble with currentIndex property. I want to do some action on

onCurrentIndexChanged:

But when I use

LayoutMirroring.enabled: true

currentIndex is not updated anymore. There is no action in onCurrentIndexChanged and currentIndex is equal to 0 all the time.
I've also tried to use

layoutDirection: Qt.RightToLeft
but problem is the same ( no currentIndex updates when listView is moved).

I've read ListView documentation and there was information, that if you use

snapMode: ListView.SnapToItem

you also need to add

highlightRangeMode:  ListView.StrictlyEnforceRange

in order to currentIndex is update properly. Maybe there is something similar for mirror layout?

Here is the whole code:

ListView
    {
        id: id_couplingControlView

        model: id_multiCouplingMeasurePopup.p_iCouplingsCount
        orientation: ListView.Horizontal
        snapMode: ListView.SnapToItem
        highlightRangeMode:  ListView.StrictlyEnforceRange          //To update the currentIndex as the list is moved
        preferredHighlightBegin: id_multiCouplingMeasurePopup.p_bViewRotated ? id_couplingControlView.width : id_couplingControlView.leftMargin
        LayoutMirroring.enabled:  id_multiCouplingMeasurePopup.p_bViewRotated
        //layoutDirection: id_multiCouplingMeasurePopup.p_bViewRotated ? Qt.RightToLeft : Qt.LeftToRight

        delegate: QmlSHMultiCouplingMeasureControl
        {
            id: id_CouplingMeasureControl

            p_iIndex: index
            Component.onCompleted:
            {
                InitializeCouplingControl ( id_CouplingMeasureControl )
            }
        }

        //Need to to something here
        onCurrentIndexChanged:
        {
            console.log ( "onCurrentIndexChanged:: " + id_couplingControlView.currentIndex )
            id_multiCouplingMeasurePopup.UpdateMiniTrainCouplingList( id_couplingControlView.currentIndex );
        }
    }

So my question is: what I need to do to have currentIndex updated while scrolling listView when using LayoutMirroring.enabled: true or layoutDirection: Qt.RightToLeft.

Body:
If you had provided a Minimal, Complete and Verifyable Example we might have come down to the core of your problem.

So to answer your question: You need to do, exactly what you assumed:

Make the ListView horizontal: orientation: ListView.Horizontal

Enable mirroring: LayoutMirroring.enabled: true

Snap to Item: snapMode: ListView.SnapToItem <= Actually seems optional

enforce the currenItem to be in the view: highlightRangeMode:  ListView.StrictlyEnforceRange

This is how a MCVE could look like, that proves that it works as expected:

ListView {
    id: lv
    model: 100
    LayoutMirroring.enabled: true
    orientation: ListView.Horizontal
    width: 500
    height: 100
    spacing: 5
    snapMode: ListView.SnapToItem
    highlightRangeMode:  ListView.StrictlyEnforceRange
    onCurrentIndexChanged: console.log('Current Index changed to', currentIndex)

    delegate: Rectangle {
        width: 100
        height: 100
        color: lv.currentItem === this ? Qt.rgba(1, 0, 0, 1) : Qt.rgba(0, 0, 1, index / 200 + 0.5)
    }
}


答:
You're running the code in python 2. That explains the braces being printed. Run in python 3 it'll work as you expect. Or if you still prefer python 2,then just remove the braces and put</p>

```<code>print n,' is the magicnumber'
</code>```

Title: Print output not showing the correct format

Body:
You're running the code in python 2. That explains the braces being printed. Run in python 3 it'll work as you expect. Or if you still prefer python 2,then just remove the braces and put

print n,' is the magicnumber'


答:
Problem solved by disabling "SELECT SQL_CALC_FOUND_ROWS" query that solution found in this post
"WordPress: SQL_CALC_FOUND_ROWS, why it’s slow and what to do about it"</p>

Title: Wordpress theme generate error for mysql SELECT SQL_CALC_FOUND_ROWS

Body:
Wordpress theme generate following error for mysql:

####
+---------+------------------+-------------------+-----------------------+---------+--------+------------+------------------------------------------------------------------------------------------------------+----------+
| Id      | User             | Host      | db               |Command| Time   | State      | Info                                                                                | Progress |
+---------+------------------+-------------------+-----------------------+---------+--------+------------+------------------------------------------------------------------------------------------------------+----------+
| 9013075 | nilamigh_nilami2 | localhost | nilamigh_nilami2 | Query | 116398 | statistics | SELECT SQL_CALC_FOUND_ROWS wpli_sbafat18posts.ID FROM wpli_sbafat18posts LEFT JOIN wpli_sbafat18te | 0.000 |
| 9014193 | nilamigh_nilami2 | localhost | nilamigh_nilami2 | Query | 116097 | statistics | SELECT SQL_CALC_FOUND_ROWS wpli_sbafat18posts.ID FROM wpli_sbafat18posts LEFT JOIN wpli_sbafat18te | 0.000 |

####


问:
Collapsing margin on an absolutely positioned div?
I have 4 div's total:

1 container
1 submenu
1 content
1 sidebar

They are set up as so:

```<code><container>
     <submenu></submenu>
     <content></content>
     <sidebar></sidebar>
</container>
</code>```

The container has position:relative and overflow:hidden

submenu and conent has float:left with margins used to position

sidebar is absolutely positioned to the right (float will not work since the subbar affects the layout.

I have images that are listed vertically inside the sidebar but they are cut off by the container. if I float or set position to relative it will contain the sidebar properly. I've tried a clear fix after the side bar but that doesn't work.

This is one of those issues I always see to have problems with. Any suggestions?

-----edit------

```<code><div id="content">
    <div id="submenu">
    </div>
    <div id="contentBox">
    </div>
    <div id="sidebar">
    </div>
</div>

#content
{
    margin: -22px auto 0 auto;
    overflow: hidden;
    padding: 0 10px 10px 10px;
    position: relative;
    text-align: left;
    width: 961px;
}

#submenu
{
    background-color: #001a28;
    border: 5px #008da8 solid;
    float: left;
    margin: -20px 0 0 -10px;
    padding-top: 20px;
    width: 700px;
}

#contentBox
{
    background-color: #ffffff;
    float: left;
    margin: 10px 0 10px -10px;
    width: 710px;
}

#sidebar
{
    border-left: 5px #008da8 solid;
    border-right: 5px #008da8 solid;
    background-color: #ffffff;
    display: block;
    height: 100%;
    position: relative;
    float: right;
    text-align: center;
    right: 10px;
    top: -10px;
    width: 207px;
}
</code>```

答:
I haven't found an easy way to make a div 100% of the parent element's height. I've been able to cheat in the past: instead of trying to make the <sidebar> stretch to 100% height, I use a vertical background stretch in the <container> to create a stripe where the sidebar sits, and make the <sidebar> bg-transparent. That way, no matter what the height of the <sidebar> is, there will always be an illusion of it being 100% of the <container>'s height.

Once you have that, just make sure your images aren't being cropped like you described, and it should be the same effect. Though, I can't tell if this will be useful to you without knowing more about what you're trying to accomplish. Hope this helps!

ContentLicense: CC BY-SA 2.5

Body:
I have 4 div's total:

1 container
1 submenu
1 content
1 sidebar

They are set up as so:

<container>
     <submenu></submenu>
     <content></content>
     <sidebar></sidebar>
</container>

The container has position:relative and overflow:hidden

submenu and conent has float:left with margins used to position

sidebar is absolutely positioned to the right (float will not work since the subbar affects the layout.

I have images that are listed vertically inside the sidebar but they are cut off by the container. if I float or set position to relative it will contain the sidebar properly. I've tried a clear fix after the side bar but that doesn't work.

This is one of those issues I always see to have problems with. Any suggestions?

-----edit------

#content
{
    margin: -22px auto 0 auto;
    overflow: hidden;
    padding: 0 10px 10px 10px;
    position: relative;
    text-align: left;
    width: 961px;
}

#submenu
{
    background-color: #001a28;
    border: 5px #008da8 solid;
    float: left;
    margin: -20px 0 0 -10px;
    padding-top: 20px;
    width: 700px;
}

#contentBox
{
    background-color: #ffffff;
    float: left;
    margin: 10px 0 10px -10px;
    width: 710px;
}

#sidebar
{
    border-left: 5px #008da8 solid;
    border-right: 5px #008da8 solid;
    background-color: #ffffff;
    display: block;
    height: 100%;
    position: relative;
    float: right;
    text-align: center;
    right: 10px;
    top: -10px;
    width: 207px;
}


问:
What are the differences between > and space?
What are the differences between these two styles :

```<code>element1 > element2 {
   ...
}
</code>```

and

```<code>element1 element2 {
   ...
}
</code>```

答:
> is the child combinator which signifies a direct child while a space (or >>) is the descendant combinator, meaning the other element can be anywhere inside the first one.

If you have the following DOM tree

```<code>a
  b
    c
  d
</code>```

then a > c will match nothing, while a c will match the c element.

Body:
What are the differences between these two styles :

element1 > element2 {
   ...
}

and

element1 element2 {
   ...
}

Body:
> is the child combinator which signifies a direct child while a space (or >>) is the descendant combinator, meaning the other element can be anywhere inside the first one.

If you have the following DOM tree

a
  b
    c
  d

then a > c will match nothing, while a c will match the c element.


问:
Angular2 AoT Compiler no ngfactory files?
When using ngc in place of tsc, or when using AotPlugin from @ngtools/webpack, ngfactory files should be generated for each angular module.
But in my case the ngc succeeds silently yet no files are generated.

Can you please give me a guidance how to even investigate that if the ngc does not print any message?

I tried with typescript@2.1.6 and 2.0.2
With @angular 2.3.1 and 2.4.7.
The result is the same.

Here's my tsconfig and webpack config, too. In both cases (run webpack or run ngc) it won't create the files.

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "diagnostics": false,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "./compiled",
    "rootDir": "./"
  },
  "filesGlob": [
    "**/*.ts"
  ],
  "include": [ "typings" ],
  "exclude": [ "node_modules" ],
  "angularCompilerOptions": {
    "entryModule": "app/module#AppModule",
    "gendir": "aot",
    "skipMetadataEmit": true,
    "debug": true,
    "trace": true,
    "generateCodeForLibraries": true
  }
}
</code>```

and the webpack file:

```<code>/// <binding ProjectOpened='Watch - Development' />
var AotPlugin = require("@ngtools/webpack").AotPlugin;

var path = require("path");
var webpack = require("webpack");
var basePath = path.join(__dirname, "wwwroot");

module.exports = {
    context: basePath,
    entry: {
        main: ["./app/main.ts"],
        productModule: "./app/components/product-module",
        adminModule: "./app/components/admin-module"
'rxjs/add/operator/map', 'rxjs/add/operator/delay']
        },
        output: {
            path: path.join(__dirname, "wwwroot/built"),
            filename: "[name].bundle.js",
            sourceMapFilename: "[name].bundle.js",
            publicPath: "built/"
        },
        module: {
            rules: [
                {
                    test: /\.html$/,
                    loader: "html-loader",
                    query: {
                        minimize: true,
                        ignoreCustomFragments: [/\{\{.*?}}/],
                        removeAttributeQuotes: false,
                        caseSensitive: true,
                        customAttrSurround: [ [/#/, /(?:)/], [/\*/, /(?:)/], [/\[?\(?/, /(?:)/] ],
                        customAttrAssign: [ /\)?\]?=/ ] ,
                        root: basePath,
                        attrs: false // ['img:src', 'link:href']
                    }
                },
                {
                    test: /\.ts$/,
                    loaders: ["@ngtools/webpack"]
                }//,
               // { test: /\.css$/, loader: "style-loader!css-loader?root=." }
            ]
        },
        externals: {
            "jquery": "jQuery"
        },
        devtool: false,
        plugins: [
            new AotPlugin({
                tsConfigPath: "./tsconfig.json",
                entryModule: "app/module#AppModule"
            }),
           // new webpack.optimize.DedupePlugin(),
            new webpack.optimize.CommonsChunkPlugin({
                //filename: "[name].c.bundle.js"//,
                names: ["main"]
            })
            //,
            , new webpack.optimize.UglifyJsPlugin({
                sourceMap: true,
                minimize: true,
                acorn: true,
                angular: true,
                beautify: false,
                compress: {
                    properties: true,
                    sequences: true,
                    dead_code: true,
                    drop_debugger: true,
                    unsafe_comps: true,
                    conditionals: true,
                    comparisons: true,
                    evaluate: true,
                    booleans: true,
                    keep_fargs: false,
                    loops: true,
                    unsafe: true,
                    angular: true,
                    unused: true,
                    cascade: true,
                    hoist_funs: true,
                    join_vars: true,
                    warnings: false
                },
                output: {
                    comments: false
                }
            })
        ]

    };
</code>```

答:
I think the reason is @ngtools/webpack doesn't generate those files. </p>

<p>@ngtools/webpack handle those files in-memory and generate one file.</p>

Body:
When using ngc in place of tsc, or when using AotPlugin from @ngtools/webpack, ngfactory files should be generated for each angular module.
But in my case the ngc succeeds silently yet no files are generated.

Can you please give me a guidance how to even investigate that if the ngc does not print any message?

I tried with typescript@2.1.6 and 2.0.2
With @angular 2.3.1 and 2.4.7.
The result is the same.

Here's my tsconfig and webpack config, too. In both cases (run webpack or run ngc) it won't create the files.

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "diagnostics": false,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "./compiled",
    "rootDir": "./"
  },
  "filesGlob": [
    "**/*.ts"
  ],
  "include": [ "typings" ],
  "exclude": [ "node_modules" ],
  "angularCompilerOptions": {
    "entryModule": "app/module#AppModule",
    "gendir": "aot",
    "skipMetadataEmit": true,
    "debug": true,
    "trace": true,
    "generateCodeForLibraries": true
  }
}

and the webpack file:

/// <binding ProjectOpened='Watch - Development' />
var AotPlugin = require("@ngtools/webpack").AotPlugin;

var path = require("path");
var webpack = require("webpack");
var basePath = path.join(__dirname, "wwwroot");

module.exports = {
    context: basePath,
    entry: {
        main: ["./app/main.ts"],
        productModule: "./app/components/product-module",
        adminModule: "./app/components/admin-module"
'rxjs/add/operator/map', 'rxjs/add/operator/delay']
        },
        output: {
            path: path.join(__dirname, "wwwroot/built"),
            filename: "[name].bundle.js",
            sourceMapFilename: "[name].bundle.js",
            publicPath: "built/"
        },
        module: {
            rules: [
                {
                    test: /\.html$/,
                    loader: "html-loader",
                    query: {
                        minimize: true,
                        ignoreCustomFragments: [/\{\{.*?}}/],
                        removeAttributeQuotes: false,
                        caseSensitive: true,
                        customAttrSurround: [ [/#/, /(?:)/], [/\*/, /(?:)/], [/\[?\(?/, /(?:)/] ],
                        customAttrAssign: [ /\)?\]?=/ ] ,
                        root: basePath,
                        attrs: false // ['img:src', 'link:href']
                    }
                },
                {
                    test: /\.ts$/,
                    loaders: ["@ngtools/webpack"]
                }//,
               // { test: /\.css$/, loader: "style-loader!css-loader?root=." }
            ]
        },
        externals: {
            "jquery": "jQuery"
        },
        devtool: false,
        plugins: [
            new AotPlugin({
                tsConfigPath: "./tsconfig.json",
                entryModule: "app/module#AppModule"
            }),
           // new webpack.optimize.DedupePlugin(),
            new webpack.optimize.CommonsChunkPlugin({
                //filename: "[name].c.bundle.js"//,
                names: ["main"]
            })
            //,
            , new webpack.optimize.UglifyJsPlugin({
                sourceMap: true,
                minimize: true,
                acorn: true,
                angular: true,
                beautify: false,
                compress: {
                    properties: true,
                    sequences: true,
                    dead_code: true,
                    drop_debugger: true,
                    unsafe_comps: true,
                    conditionals: true,
                    comparisons: true,
                    evaluate: true,
                    booleans: true,
                    keep_fargs: false,
                    loops: true,
                    unsafe: true,
                    angular: true,
                    unused: true,
                    cascade: true,
                    hoist_funs: true,
                    join_vars: true,
                    warnings: false
                },
                output: {
                    comments: false
                }
            })
        ]

    };

Body:
I think the reason is @ngtools/webpack doesn't generate those files.

@ngtools/webpack handle those files in-memory and generate one file.


问:
Rotate TImage inside a procedure (without using TTimer)
I was trying to make a simple animation inside a TButton procedure of a TImage rotating from a degree to another on Android using Delphi-Firemonkey (Berlin) like this:

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
while Image1.RotationAngle < 360 do begin
Image1.RotationAngle := Image1.RotationAngle+1;
Image1.Repaint;
Sleep(1);
end;
end;
</code>```

I've tried with and without Image1.Repaint but the animation simply does not work, but when using a TTimer it works perfectly. Anyone has any idea how to solve this?

答:
Don't use any Sleep calls in the main thread, you can rotate TImage without TTimer so:

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  sText: string;
begin
  Button1.Enabled := False;
  sText := Button1.Text;
  Button1.Text := 'Wait...';
  TThread.CreateAnonymousThread(procedure
  begin
    while Image1.RotationAngle < 360 do begin
      TThread.Synchronize(nil, procedure
      begin
        Image1.RotationAngle := Image1.RotationAngle + 2;
      end);
      Sleep(10);
    end;
    TThread.Synchronize(nil, procedure
    begin
      Button1.Text := sText;
      Button1.Enabled := True;
    end);
  end).Start;
end;
</code>```

Second solution: Add Anim: TFloatAnimation to the Form:

```<code>type
  TForm1 = class(TForm)
    ...
  public
    Anim: TFloatAnimation;
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Anim.Enabled := False;
  Image1.RotationAngle := 0;
  Anim.Enabled := True;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Anim := TFloatAnimation.Create(Self);
  Anim.Parent := Self;
  Anim.Duration := 1;
  Anim.StartValue := 0;
  Anim.StopValue := 360;
  Anim.PropertyName := 'Image1.RotationAngle';
end;
</code>```

Body:
I was trying to make a simple animation inside a TButton procedure of a TImage rotating from a degree to another on Android using Delphi-Firemonkey (Berlin) like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
while Image1.RotationAngle < 360 do begin
Image1.RotationAngle := Image1.RotationAngle+1;
Image1.Repaint;
Sleep(1);
end;
end;

I've tried with and without Image1.Repaint but the animation simply does not work, but when using a TTimer it works perfectly. Anyone has any idea how to solve this?

Body:
Don't use any Sleep calls in the main thread, you can rotate TImage without TTimer so:

procedure TForm1.Button1Click(Sender: TObject);
var
  sText: string;
begin
  Button1.Enabled := False;
  sText := Button1.Text;
  Button1.Text := 'Wait...';
  TThread.CreateAnonymousThread(procedure
  begin
    while Image1.RotationAngle < 360 do begin
      TThread.Synchronize(nil, procedure
      begin
        Image1.RotationAngle := Image1.RotationAngle + 2;
      end);
      Sleep(10);
    end;
    TThread.Synchronize(nil, procedure
    begin
      Button1.Text := sText;
      Button1.Enabled := True;
    end);
  end).Start;
end;

Second solution: Add Anim: TFloatAnimation to the Form:

type
  TForm1 = class(TForm)
    ...
  public
    Anim: TFloatAnimation;
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Anim.Enabled := False;
  Image1.RotationAngle := 0;
  Anim.Enabled := True;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Anim := TFloatAnimation.Create(Self);
  Anim.Parent := Self;
  Anim.Duration := 1;
  Anim.StartValue := 0;
  Anim.StopValue := 360;
  Anim.PropertyName := 'Image1.RotationAngle';
end;


问:
Unable to access DesiredCapabilities methods
My question is :
I created DesiredCapabilities instance  shown in below code :

```<code>public class TestCommons  {

    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);

    WebDriver driver = new FirefoxDriver();

    public void setUp() {

        driver.navigate().to(
                "http://toolsqa.wpengine.com/automation-practice-form/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        System.out.println("");
    }

    public void tearDown() {

        driver.close();
    }

}
</code>```

When I write  capabilities. in the next line am not getting any eclipse intellisense options. And if I write capabilities.setCapability , its showing error.
As in the code , in setUp() method  when i write capabilities. I get options.
Why am I not getting eclipse intellisense outside the method?
Attached screenshot.DesiredCapabilities instance

答: You will get DesiredCapabilities properties are inside the Methods only not out method or inside the class.</p>

Body:
My question is :
I created DesiredCapabilities instance  shown in below code :

public class TestCommons  {

    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);

    WebDriver driver = new FirefoxDriver();

    public void setUp() {

        driver.navigate().to(
                "http://toolsqa.wpengine.com/automation-practice-form/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        System.out.println("");
    }

    public void tearDown() {

        driver.close();
    }

}

When I write  capabilities. in the next line am not getting any eclipse intellisense options. And if I write capabilities.setCapability , its showing error.
As in the code , in setUp() method  when i write capabilities. I get options.
Why am I not getting eclipse intellisense outside the method?
Attached screenshot.DesiredCapabilities instance


问:
This generic return value is not working
I am trying to return a generic ArrayList from a generic function in which i am passing a class instance but i am getting errors in type cast with the return value

below is the code:

```<code>public <T extends DefaultHandler> List<M> getItems(Class<T> handlerClass) throws Exception{
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    DefaultHandler handler = null;
    handler=handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();  // errorLine
}
</code>```

The errorline says since handler is of type DefaultHandler , it can't call the getRSSItemList() function which is in child classes of DefaultHandler

How can call this method ?

The hierarchy is like this :

```<code>Class RSSHandler1 extends DefaultHandler
{
  public List<RssItem1> getRSSItemList(){
    return rssItemList;
  }
}

Class RSSHandler2 extends DefaultHandler
{
   public List<RssItem2> getRSSItemList(){
    return rssItemList;
   }
}
</code>```

Thanks in Advance

答: Try to cast handler to T (i.e. return ((T)handler).getRSSItemList();)

Body:
I am trying to return a generic ArrayList from a generic function in which i am passing a class instance but i am getting errors in type cast with the return value

below is the code:

public <T extends DefaultHandler> List<M> getItems(Class<T> handlerClass) throws Exception{
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    DefaultHandler handler = null;
    handler=handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();  // errorLine
}

The errorline says since handler is of type DefaultHandler , it can't call the getRSSItemList() function which is in child classes of DefaultHandler

How can call this method ?

The hierarchy is like this :

Class RSSHandler1 extends DefaultHandler
{
  public List<RssItem1> getRSSItemList(){
    return rssItemList;
  }
}

Class RSSHandler2 extends DefaultHandler
{
   public List<RssItem2> getRSSItemList(){
    return rssItemList;
   }
}

Thanks in Advance


问:
How to set time of java.util.Date instance to 00:00:00?
I have a variable of the type java.util.Date.

How can I set the time part to 00:00:00?

I am not allowed to use an Apache Commons library or JodaTime. The java.util.Calendar is probably my only option.

答:
In Java 8 'java.time.LocalDate.atStartOfDay()' can be used too:</p>

```<code>    Date date = new Date();
    Instant inst = date.toInstant();
    LocalDate localDate = inst.atZone(ZoneId.systemDefault()).toLocalDate();
    Instant dayInst = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date day = Date.from(dayInst);
</code>```

Body:
In Java 8 'java.time.LocalDate.atStartOfDay()' can be used too:

    Date date = new Date();
    Instant inst = date.toInstant();
    LocalDate localDate = inst.atZone(ZoneId.systemDefault()).toLocalDate();
    Instant dayInst = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date day = Date.from(dayInst);


答:
element1 > element2 selects all <element2> elements where the parent is a <element1> element (see child combinator selector for more information) while element1 element2 selects all <element2> elements inside <element1> elements (see descendant selector for more information).

Example:

If you have to following DOM markup (see this JSFiddle):

```<code>a
  c
  b
    c
  d
    c
</code>```

And you use a c {bg -> red} (pseudo-code) all c elements will turn red, but if you also use a > c {bg -> blue} the first c element will turn blue while the other will be red. This is because the a element is the direct parent of the first c element.

Title: What are the differences between > and space?

Body:
element1 > element2 selects all <element2> elements where the parent is a <element1> element (see child combinator selector for more information) while element1 element2 selects all <element2> elements inside <element1> elements (see descendant selector for more information).

Example:

If you have to following DOM markup (see this JSFiddle):

a
  c
  b
    c
  d
    c

And you use a c {bg -> red} (pseudo-code) all c elements will turn red, but if you also use a > c {bg -> blue} the first c element will turn blue while the other will be red. This is because the a element is the direct parent of the first c element.


问:
getting my divs to flow horizontally
Regardless of what I've tried, I cannot get my inner divs to flow horizonatally within the outer div. Please help!!!</p>

```<code><style type="text/css">

#gallery {
width: 688px;
height: 360px;
border: solid;
}

#galleryelements {
width: 650px;
height: 320px;
display:inline;
background-color:#0FF;
}

.s-thumbnail {
width: 50px;
height: 75px;
border: solid;
}

.thumbnail {
width: 100px;
height: 150px;
border: solid;
}

#left {
float:left;
}

#right {
float:right;
}

#Mimage {
width: 200px;
height: 300px;
border: solid;
}
</style>

<body>
<div id="gallery">
<div id="galleryelements">
<div class="s-thumbnail" id="left"></div>
<div class="thumbnail" id="left"></div>
<div id="Mimage"></div>
<div class="thumbnail" id="right"></div>
<div class="s-thumbnail" id="right"></div>
</div>
</div>
</body>
</html>
</code>```

答:
is this what you mean?
http://jsfiddle.net/SebastianPataneMasuelli/xtdsv/

HTML:

```<code><div id="gallery">
    <div id="galleryelements">
        <div class="s-thumbnail left" id=""></div>
        <div class="thumbnail left" id="left"></div>
        <div id="Mimage"></div>
        <div class="thumbnail right" id=""></div>
        <div class="s-thumbnail right" id=""></div>
    </div>
</div>
</code>```

CSS:

```<code>#gallery {
    width: 688px;
    height: 360px;
    border: 1px solid red;
}

#galleryelements {
    width: 650px;
    height: 320px;
    background-color:#0FF;
    display: block;
}

.s-thumbnail {
    width: 50px;
    height: 75px;
    border: solid;
}

.thumbnail {
    width: 100px;
    height: 150px;
    border: solid;
}

.left {
    float:left;
}

.right {
    float:left;
}

#Mimage {
    width: 200px;
    height: 300px;
    border: 1px solid green;
   float: left;
}
</code>```

Title: getting my divs to flow horizontally

Body:
is this what you mean?
http://jsfiddle.net/SebastianPataneMasuelli/xtdsv/

HTML:

<div id="gallery">
    <div id="galleryelements">
        <div class="s-thumbnail left" id=""></div>
        <div class="thumbnail left" id="left"></div>
        <div id="Mimage"></div>
        <div class="thumbnail right" id=""></div>
        <div class="s-thumbnail right" id=""></div>
    </div>
</div>

CSS:

#gallery {
    width: 688px;
    height: 360px;
    border: 1px solid red;
}

#galleryelements {
    width: 650px;
    height: 320px;
    background-color:#0FF;
    display: block;
}

.s-thumbnail {
    width: 50px;
    height: 75px;
    border: solid;
}

.thumbnail {
    width: 100px;
    height: 150px;
    border: solid;
}

.left {
    float:left;
}

.right {
    float:left;
}

#Mimage {
    width: 200px;
    height: 300px;
    border: 1px solid green;
   float: left;
}


问:
Convert to date MongoDB via mongoimport
I have downloaded huge chunks of data in the format  in csv. I am using mongoimport to enter the data into MongoDB for processing.
How do I get the date into date format recognized by MongoDB?

sample data with header

```<code>Date, Open Price, High Price, Low Price, Last Traded Price , Close Price, Total Traded Quantity, Turnover (in Lakhs)
04-Apr-2014,901,912,889.5,896.75,892.85,207149,1867.08
03-Apr-2014,908,918,897.65,900,900.75,156260,1419.9
02-Apr-2014,916,921.85,898,900.7,900.75,175990,1591.97
</code>```

答:
As of Mongo version 3.4, you can use --columnsHaveTypes option to specify the type of your field while using mongoimport to import your data.
here is the link for reference.

Sample mongoimport syntax below:

```<code>mongoimport --db XYZ --collection abc --type tsv --fields id.int32(),client_name.string(),app_name.auto(),date.date() --columnsHaveTypes --file "abc.tsv" --verbose
</code>```

Title: Convert to date MongoDB via mongoimport

Body:
I have downloaded huge chunks of data in the format  in csv. I am using mongoimport to enter the data into MongoDB for processing.
How do I get the date into date format recognized by MongoDB?

sample data with header

Date, Open Price, High Price, Low Price, Last Traded Price , Close Price, Total Traded Quantity, Turnover (in Lakhs)
04-Apr-2014,901,912,889.5,896.75,892.85,207149,1867.08
03-Apr-2014,908,918,897.65,900,900.75,156260,1419.9
02-Apr-2014,916,921.85,898,900.7,900.75,175990,1591.97

Body:
As of Mongo version 3.4, you can use --columnsHaveTypes option to specify the type of your field while using mongoimport to import your data.
here is the link for reference.

Sample mongoimport syntax below:

mongoimport --db XYZ --collection abc --type tsv --fields id.int32(),client_name.string(),app_name.auto(),date.date() --columnsHaveTypes --file "abc.tsv" --verbose