问:
Error when try to update text in French/English to mysql db
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

```<code><?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "<script>alert ('Editado com sucesso'); window.location='admin_biografia.php'</script>";
        }
    }
?>

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>
    </head>
    <body>
        <div class="col-2"></div>
        <div class="col-8">
                <div class="col-12 w3-card-4 nopadding">
                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">ID</div>
                            <div class="w3-rest">
                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Título FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Legenda FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Texto FR</div>
                            <div class="w3-rest">
                                <div class="w3-rest">
                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>
                            </div>
                            </div>
                        </div>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>
                </div>
            </div>
            <div class="col-2"></div>
        </body>
</html>
</code>```

答:
Replace your code with this. Hope it helps. Thanks. Use mysql_real_escape_string to escape special characters and remove {} in your query for php variable.    </p>

```<code>if ($_POST)
{
    $id = $_POST['id'];
    $title_fr = mysql_real_escape_string($_POST['title_fr']);
    $subtitle_fr = mysql_real_escape_string($_POST['subtitle_fr']);
    $text_fr = mysql_real_escape_string($_POST['text_fr']);

    $q = mysql_query ("UPDATE tb_biografia SET title_fr='$title_fr', subtitle_fr='$subtitle_fr', text_fr='$text_fr'  WHERE id='$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

    if($q){
        echo "<script>alert ('Editado com sucesso'); window.location='admin_biografia.php'</script>";
    }
}
</code>```

Body:
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

<?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "";
        }
    }
?>

        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>

                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />

ID

                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">

Título FR

                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">

Legenda FR

                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">

Texto FR

                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>

Body:
Replace your code with this. Hope it helps. Thanks. Use mysql_real_escape_string to escape special characters and remove {} in your query for php variable.

if ($_POST)
{
    $id = $_POST['id'];
    $title_fr = mysql_real_escape_string($_POST['title_fr']);
    $subtitle_fr = mysql_real_escape_string($_POST['subtitle_fr']);
    $text_fr = mysql_real_escape_string($_POST['text_fr']);

    $q = mysql_query ("UPDATE tb_biografia SET title_fr='$title_fr', subtitle_fr='$subtitle_fr', text_fr='$text_fr'  WHERE id='$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

    if($q){
        echo "<script>alert ('Editado com sucesso'); window.location='admin_biografia.php'</script>";
    }
}


来源: stackexchange

问:
Label prediction to probability score prediction/AUC using scikit-learn SVM
For a DS competition I was using SVM to do binary classification. Here tdata,vdata both have 256 features. tlabels,vlabels both have dimensions n_samples x 1 and their unique values are 0/1.

Now, as per the competition rules, in place of labels, we need to submit probability score(between 0 to 1) and AUC will be used to decide the ranking.

I am pretty new to SVMs and Sklearn. Any pointers on how to convert this code to generate probability scores and AUC, will be of great help.

Code:

```<code>classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced')
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
cm = metrics.confusion_matrix(expected, predicted)
accuracy = (cm[0,0]+cm[1,1])*100.0/sum(sum(cm))
print("accuracy = "+str(accuracy))
</code>```

Output:

```<code>Classification report for classifier SVC(C=1.0, cache_size=200, class_weight='balanced', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.00020000000000000001,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False):
             precision    recall  f1-score   support

        0.0       0.93      0.88      0.90      1881
        1.0       0.92      0.95      0.94      2686

avg / total       0.92      0.92      0.92      4567

accuracy = 92.3144296037
</code>```

答:
Use predict_proba function of SVC for obtaining probabilities instead of classes.

To use predict_proba function on SVC parameter probability=True should be given while initalization.

```<code>classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced', probability=True) # parameter probability=True should be given
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)
pred_proba = classifier.predict_proba(vdata) # predict_proba function call

fpr, tpr, thresholds = metrics.roc_curve(labels, proba_one)
metrics.auc(fpr, tpr)
</code>```

Reference:

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html

http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

ContentLicense: CC BY-SA 3.0

Body:
For a DS competition I was using SVM to do binary classification. Here tdata,vdata both have 256 features. tlabels,vlabels both have dimensions n_samples x 1 and their unique values are 0/1.

Now, as per the competition rules, in place of labels, we need to submit probability score(between 0 to 1) and AUC will be used to decide the ranking.

I am pretty new to SVMs and Sklearn. Any pointers on how to convert this code to generate probability scores and AUC, will be of great help.

Code:

classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced')
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
cm = metrics.confusion_matrix(expected, predicted)
accuracy = (cm[0,0]+cm[1,1])*100.0/sum(sum(cm))
print("accuracy = "+str(accuracy))

Output:

Classification report for classifier SVC(C=1.0, cache_size=200, class_weight='balanced', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.00020000000000000001,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False):
             precision    recall  f1-score   support

        0.0       0.93      0.88      0.90      1881
        1.0       0.92      0.95      0.94      2686

avg / total       0.92      0.92      0.92      4567

accuracy = 92.3144296037

Body:
Use predict_proba function of SVC for obtaining probabilities instead of classes.

To use predict_proba function on SVC parameter probability=True should be given while initalization.

classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced', probability=True) # parameter probability=True should be given
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)
pred_proba = classifier.predict_proba(vdata) # predict_proba function call

fpr, tpr, thresholds = metrics.roc_curve(labels, proba_one)
metrics.auc(fpr, tpr)

Reference:

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html

http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html


问:
SCSS: concat files but not compile
I'm looking for easy way to concat scss files(that contain imports) into single scss file,

not compile but concat.

More details:
Our SCSS is compiled on-fly based on variables from database, so it it's not possible to compile it before deployment. But I still would like to do some optimizations to help server-side compiler - to concat many files into single one.

答:
How about using grunt-contrib-concat to only concat as you mentioned:

```<code>concat: {
    dist: {
        src: [
            'sass/*.scss',
        ],
        dest: 'sass/build.scss',
    }
}
</code>```

ref: https://github.com/gruntjs/grunt-contrib-concat#concat-task

Title: SCSS: concat files but not compile

Body:
How about using grunt-contrib-concat to only concat as you mentioned:

concat: {
    dist: {
        src: [
            'sass/*.scss',
        ],
        dest: 'sass/build.scss',
    }
}

ref: https://github.com/gruntjs/grunt-contrib-concat#concat-task


问:
Javascript RegEx : Match repeating character exactly twice (ignore if it matches 3 times)
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

```<code>\{\{[^\{]([\s\S]+?)[^\}]\}\}
</code>```

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?

答:
RegEx:
^(\}?)\{\{[^\{]([\s\S]+?)[^\}]\}\}

Auto Generated Explanation:

^ asserts position at start of the string
1st Capturing Group (\}?)
\}? matches the character } literally (case sensitive)
? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
\{ matches the character { literally (case sensitive)
\{ matches the character { literally (case sensitive)
Match a single character not present in the list below [^\{]
\{ matches the character { literally (case sensitive)
2nd Capturing Group ([\s\S]+?)
Match a single character present in the list below [\s\S]+?
+? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
\s matches any whitespace character (equal to [\r\n\t\f\v ])
\S matches any non-whitespace character (equal to [^\r\n\t\f ])
Match a single character not present in the list below [^\}]
\} matches the character } literally (case sensitive)
\} matches the character } literally (case sensitive)
\} matches the character } literally (case sensitive)
Global pattern flags
g modifier: global. All matches (don't return after first match)

Body:
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

\{\{[^\{]([\s\S]+?)[^\}]\}\}

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?


问:
save calculator result and show them as a list using SharedPreferences
i have successfully implemented a calculator with a history activity in which it will show old results in a list view
but i am facing a problem that the first line is always null

https://imgur.com/a/jvXms

i tried to make default string " Old Calculation "

```<code>>    String w = "Old Calculation";
</code>```

but this didn't work,
my app save the result in a multiline String in SharedPreferences and pass it to another activity through an intent

```<code>>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute
</code>```

under the onCreate i set the String value to sharedpref

```<code>> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        w = prefs.getString("saved", null);
</code>```

update method in which i update the result string value with the String s( String s is the calculated result)

```<code>>     public void update(String s){
        editor= getPreferences(MODE_PRIVATE).edit();
        w =     w
                + System.getProperty ("line.separator")
                + s
                + System.getProperty ("line.separator");
        editor.putString("saved", w);
        editor.apply();
    }
</code>```

Passing W value to the activity in which i will show the result in TextView list

```<code>>    public void History(View v){
        Intent myIntent = new Intent(MainActivity.this, History.class);
        myIntent.putExtra("message", w);
        startActivity(myIntent);
        overridePendingTransition(R.anim.anim_slide_in_left,
        R.anim.anim_slide_out_left);
    }
</code>```

History activity

```<code>    public class History extends AppCompatActivity {
    TextView tv1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        String w ="Old calculation is showed here";
        tv1 = (TextView) findViewById(R.id.tv1);
        print(w);
    }

    public void print(String w) {
            Bundle bundle = getIntent().getExtras();
            w = bundle.getString("message");

            tv1.setMovementMethod(new ScrollingMovementMethod());

            tv1.setText(w);

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
    }
    public void deleteAppData(View v) {
        try {
            // clearing app data
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
when you store data from activity A and you want  retrieve it from another activity, You must use SharedPreferences as below:

SharedPreferences prefs = getSharedPreferences(String, int);

String is FileName like "result"

int is Mode like MODE_PRIVATE

for example see this link

in addition i wrote a simple code for help you

Body:
i have successfully implemented a calculator with a history activity in which it will show old results in a list view
but i am facing a problem that the first line is always null

https://imgur.com/a/jvXms

i tried to make default string " Old Calculation "

>    String w = "Old Calculation";

but this didn't work,
my app save the result in a multiline String in SharedPreferences and pass it to another activity through an intent

>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute

under the onCreate i set the String value to sharedpref

> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        w = prefs.getString("saved", null);

update method in which i update the result string value with the String s( String s is the calculated result)

>     public void update(String s){
        editor= getPreferences(MODE_PRIVATE).edit();
        w =     w
                + System.getProperty ("line.separator")
                + s
                + System.getProperty ("line.separator");
        editor.putString("saved", w);
        editor.apply();
    }

Passing W value to the activity in which i will show the result in TextView list

>    public void History(View v){
        Intent myIntent = new Intent(MainActivity.this, History.class);
        myIntent.putExtra("message", w);
        startActivity(myIntent);
        overridePendingTransition(R.anim.anim_slide_in_left,
        R.anim.anim_slide_out_left);
    }

History activity

    public class History extends AppCompatActivity {
    TextView tv1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        String w ="Old calculation is showed here";
        tv1 = (TextView) findViewById(R.id.tv1);
        print(w);
    }

    public void print(String w) {
            Bundle bundle = getIntent().getExtras();
            w = bundle.getString("message");

            tv1.setMovementMethod(new ScrollingMovementMethod());

            tv1.setText(w);

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
    }
    public void deleteAppData(View v) {
        try {
            // clearing app data
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
How does one handle foreign key constraints from within a symfony application?
Maybe I've just been entirely ignorant to the solution to my issue and, hell, maybe it's built-in... I just haven't been able to find such a solution. I've been looking passively for the last two weeks and actively for the last day.

How can I gracefully handle a foreign key constraint in symfony?

I've considered catching the exception (Doctrine_Connection_Exception) and assuming it was a foreign key constraint, then forwarding the user to an error module with an action for foreign key constraints. However, the code redundancy is atrocious and, even if I do put it into my base action class, having to put a try-catch block around each call to the database would get ugly. Not to mention, the assumption the exception is for a foreign key constraint is a horrible idea since this exception is called when there's SQL syntax and actual connection errors, as well.

I've thought about using the getPortableCode() and getPortableMessage() methods--which are inherited from the exception class--to determine if it's a foreign key constraint (which they can do) but they give absolutely no information about the constraint itself. For instance, when a constraint exception is thrown, getPortableCode() returns '-5' and getPortableMessage() returns 'already exists'. Granted, I could probably figure out what failed and throw up an error for my user if there was a single constraint, but, of course, I've made things complicated with multiple constraints.

Anyway, enough of my rambling, I'm trying to figure out what other developers are doing in my situation... It seems like this should be something covered in the lackluster "gentle introduction."

答:
The answer to this question depends on what's creating the database entries.

If the answer is a form submission, you should be using Symfony's validation system. Doctrine provides validators for checking whether a relation is valid or an object exists. Take a look at sfValidatorDoctrineChoice and sfValidatorDoctrineUnique.

If you're creating the database entries not based on user input, the solution here is to perform the check yourself, either via a validator or a manual DB call. I suppose you could try/catch as well.

ContentLicense: CC BY-SA 2.5


问:
You must register external thread with PjSip thread before making any call
When navigating through app app got crashed due to pjsip and it's says you must register external thread with pjsip thread. I've also regsitered pjsip with the main thread like this

```<code>  try {
            mEndpoint.libRegisterThread(Thread.currentThread().getName());
            Log.d(TAG, "Registering with thread "+Thread.currentThread().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

This crashed happend so randomly and don't exactly know what causing this and I also not calling any pjsip method when that crashed happend. So what's going wrong here?

```<code>07-04 14:36:18.183 32089-32097/com.safarifone.waafi A/libc: ../src/pj/os_core_unix.c:692: pj_thread_this: assertion "!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."" failed
    07-04 14:36:18.183 32089-32097/com.safarifone.waafi A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 32097 (FinalizerDaemon)
    07-04 14:36:18.193 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.203 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.213 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.243 326-326/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    07-04 14:36:18.243 326-326/? A/DEBUG: Build fingerprint: 'samsung/grandpplteser/grandpplte:6.0.1/MMB29T/G532FXWU1APK6:user/release-keys'
    07-04 14:36:18.243 326-326/? A/DEBUG: Revision: '0'
    07-04 14:36:18.243 326-326/? A/DEBUG: ABI: 'arm'
    07-04 14:36:18.243 326-326/? A/DEBUG: pid: 32089, tid: 32097, name: FinalizerDaemon  >>> com.safarifone.waafi <<<
    07-04 14:36:18.243 326-326/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
    07-04 14:36:18.273 326-326/? A/DEBUG: Abort message: '../src/pj/os_core_unix.c:692: pj_thread_this: assertion "!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."" failed'
    07-04 14:36:18.273 326-326/? A/DEBUG:     r0 00000000  r1 00007d61  r2 00000006  r3 b37c2978
    07-04 14:36:18.273 326-326/? A/DEBUG:     r4 b37c2980  r5 b37c2930  r6 0000000b  r7 0000010c
    07-04 14:36:18.273 326-326/? A/DEBUG:     r8 00000000  r9 b4424f00  sl b37c1b20  fp b37c1a64
    07-04 14:36:18.273 326-326/? A/DEBUG:     ip 00000006  sp b37c19d0  lr b6d4cdcd  pc b6d4f1bc  cpsr 400e0010
    07-04 14:36:18.293 326-326/? A/DEBUG: backtrace:
    07-04 14:36:18.293 326-326/? A/DEBUG:     #00 pc 000431bc  /system/lib/libc.so (tgkill+12)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #01 pc 00040dc9  /system/lib/libc.so (pthread_kill+32)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #02 pc 0001c7e7  /system/lib/libc.so (raise+10)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #03 pc 00019a65  /system/lib/libc.so (__libc_android_abort+34)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #04 pc 00017600  /system/lib/libc.so (abort+4)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #05 pc 0001b3fb  /system/lib/libc.so (__libc_fatal+16)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #06 pc 00019aed  /system/lib/libc.so (__assert2+20)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #07 pc 0034be3c  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pj_thread_this+84)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #08 pc 0034c9b8  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pj_mutex_lock+124)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #09 pc 001931c0  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (PJSUA_LOCK+32)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #10 pc 00194e1c  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pjsua_acc_set_user_data+268)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #11 pc 00156464  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN2pj7AccountD2Ev+232)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #12 pc 000d6584  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN20SwigDirector_AccountD2Ev+116)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #13 pc 000d65fc  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN20SwigDirector_AccountD0Ev+20)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #14 pc 00114764  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (Java_org_pjsip_pjsua2_pjsua2JNI_delete_1Account+76)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #15 pc 000ea539  /system/lib/libart.so (art_quick_generic_jni_trampoline+40)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #16 pc 000e5e41  /system/lib/libart.so (art_quick_invoke_stub_internal+64)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #17 pc 003e92d9  /system/lib/libart.so (art_quick_invoke_static_stub+172)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #18 pc 00101c4c  [stack:32097]
</code>```

答:
Looks like one of PjSip objects is getting collected by GC from the thread other than the one you've registered.

According to documentation:

```<code>... application ‘’‘MUST immediately destroy PJSUA2 objects using object’s delete()
method (in Java)’‘’, instead of relying on the GC to clean up the object
</code>```

So you MUST delete PjSip objects manually, for example:

```<code>account.delete();
</code>```

Link to GC issue in official documentation

Body:
When navigating through app app got crashed due to pjsip and it's says you must register external thread with pjsip thread. I've also regsitered pjsip with the main thread like this

  try {
            mEndpoint.libRegisterThread(Thread.currentThread().getName());
            Log.d(TAG, "Registering with thread "+Thread.currentThread().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

This crashed happend so randomly and don't exactly know what causing this and I also not calling any pjsip method when that crashed happend. So what's going wrong here?

07-04 14:36:18.183 32089-32097/com.safarifone.waafi A/libc: ../src/pj/os_core_unix.c:692: pj_thread_this: assertion "!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."" failed
    07-04 14:36:18.183 32089-32097/com.safarifone.waafi A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 32097 (FinalizerDaemon)
    07-04 14:36:18.193 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.203 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.213 32089-32089/com.safarifone.waafi D/ContactListAdapter: user which is recently added and not sync...
    07-04 14:36:18.243 326-326/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    07-04 14:36:18.243 326-326/? A/DEBUG: Build fingerprint: 'samsung/grandpplteser/grandpplte:6.0.1/MMB29T/G532FXWU1APK6:user/release-keys'
    07-04 14:36:18.243 326-326/? A/DEBUG: Revision: '0'
    07-04 14:36:18.243 326-326/? A/DEBUG: ABI: 'arm'
    07-04 14:36:18.243 326-326/? A/DEBUG: pid: 32089, tid: 32097, name: FinalizerDaemon  >>> com.safarifone.waafi <<<
    07-04 14:36:18.243 326-326/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
    07-04 14:36:18.273 326-326/? A/DEBUG: Abort message: '../src/pj/os_core_unix.c:692: pj_thread_this: assertion "!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."" failed'
    07-04 14:36:18.273 326-326/? A/DEBUG:     r0 00000000  r1 00007d61  r2 00000006  r3 b37c2978
    07-04 14:36:18.273 326-326/? A/DEBUG:     r4 b37c2980  r5 b37c2930  r6 0000000b  r7 0000010c
    07-04 14:36:18.273 326-326/? A/DEBUG:     r8 00000000  r9 b4424f00  sl b37c1b20  fp b37c1a64
    07-04 14:36:18.273 326-326/? A/DEBUG:     ip 00000006  sp b37c19d0  lr b6d4cdcd  pc b6d4f1bc  cpsr 400e0010
    07-04 14:36:18.293 326-326/? A/DEBUG: backtrace:
    07-04 14:36:18.293 326-326/? A/DEBUG:     #00 pc 000431bc  /system/lib/libc.so (tgkill+12)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #01 pc 00040dc9  /system/lib/libc.so (pthread_kill+32)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #02 pc 0001c7e7  /system/lib/libc.so (raise+10)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #03 pc 00019a65  /system/lib/libc.so (__libc_android_abort+34)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #04 pc 00017600  /system/lib/libc.so (abort+4)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #05 pc 0001b3fb  /system/lib/libc.so (__libc_fatal+16)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #06 pc 00019aed  /system/lib/libc.so (__assert2+20)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #07 pc 0034be3c  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pj_thread_this+84)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #08 pc 0034c9b8  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pj_mutex_lock+124)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #09 pc 001931c0  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (PJSUA_LOCK+32)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #10 pc 00194e1c  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (pjsua_acc_set_user_data+268)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #11 pc 00156464  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN2pj7AccountD2Ev+232)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #12 pc 000d6584  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN20SwigDirector_AccountD2Ev+116)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #13 pc 000d65fc  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (_ZN20SwigDirector_AccountD0Ev+20)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #14 pc 00114764  /data/app/com.safarifone.waafi-2/lib/arm/libpjsua2.so (Java_org_pjsip_pjsua2_pjsua2JNI_delete_1Account+76)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #15 pc 000ea539  /system/lib/libart.so (art_quick_generic_jni_trampoline+40)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #16 pc 000e5e41  /system/lib/libart.so (art_quick_invoke_stub_internal+64)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #17 pc 003e92d9  /system/lib/libart.so (art_quick_invoke_static_stub+172)
    07-04 14:36:18.293 326-326/? A/DEBUG:     #18 pc 00101c4c  [stack:32097]

Body:
Looks like one of PjSip objects is getting collected by GC from the thread other than the one you've registered.

According to documentation:

... application ‘’‘MUST immediately destroy PJSUA2 objects using object’s delete()
method (in Java)’‘’, instead of relying on the GC to clean up the object

So you MUST delete PjSip objects manually, for example:

account.delete();

Link to GC issue in official documentation


问:
Bootstrap 3 carousel transition speed
I'm running into a problem.

I've tried to do the following:

```<code>.carousel-inner > .item {
 position: relative;
 display: none;
 -webkit-transition: 0.6s ease-in-out left;
 -moz-transition: 0.6s ease-in-out left;
 -o-transition: 0.6s ease-in-out left;
 transition: 0.6s ease-in-out left;
}

In the bootstrap.js:

.emulateTransitionEnd(600)
</code>```

But it doesn't seem to work properly. The animation speeds up. But I use a carousel-caption that contains text, which bugs. It slides properly, but then the .content-caption moves all the way to the left, disappears, and appears in it's normal position.

Is there any other variable I need to change?

答:
Those using bootstrap 4 scss can use this variable :)</p>

```<code>$carousel-transition:           transform .6s ease-in-out !default;
</code>```

Title: Bootstrap 3 carousel transition speed

Body:
I'm running into a problem.

I've tried to do the following:

.carousel-inner > .item {
 position: relative;
 display: none;
 -webkit-transition: 0.6s ease-in-out left;
 -moz-transition: 0.6s ease-in-out left;
 -o-transition: 0.6s ease-in-out left;
 transition: 0.6s ease-in-out left;
}

In the bootstrap.js:

.emulateTransitionEnd(600)

But it doesn't seem to work properly. The animation speeds up. But I use a carousel-caption that contains text, which bugs. It slides properly, but then the .content-caption moves all the way to the left, disappears, and appears in it's normal position.

Is there any other variable I need to change?

Body:
Those using bootstrap 4 scss can use this variable :)

$carousel-transition:           transform .6s ease-in-out !default;


问:
OpenCV: wrap image to cylindrical coordinates
I'm trying to create a panoramic image using opencv library. Based on this, I need to warp the image to cylindrical coordinates. I got the formula to convert 3D cartesian (X,Y,Z) to cylindrical coordinate(θ,v) from Panoramic Image Mosaic paper , which is:

```<code>  θ = tan−1 (X/Z)

  v = Y/ √ (X^2 + Z^2)
</code>```

I have read an opencv mailing list thread about cylindrical image warping, but based on the paper, I don't think I need to use camera calibration matrix. And, in the website, the problem has not been solved. Th question is, how can we convert an opencv IplImage to cylindrical coordinate and display them correctly?

Thanks in advance.

答:
Unfortunately, you do need the camera calibration if you wish to warp an image from Cartesian to cylindrical coordinates.

Think about it. If the camera is not calibrated, then you do not know what is the field of view of the camera. If you do not the field of view, then you can not map pixels to optical rays. If you do not know the optical ray which corresponds to your pixel, there's no way to express that pixel in cylindrical coordinates.

Body:
I'm trying to create a panoramic image using opencv library. Based on this, I need to warp the image to cylindrical coordinates. I got the formula to convert 3D cartesian (X,Y,Z) to cylindrical coordinate(θ,v) from Panoramic Image Mosaic paper , which is:

  θ = tan−1 (X/Z)

  v = Y/ √ (X^2 + Z^2)

I have read an opencv mailing list thread about cylindrical image warping, but based on the paper, I don't think I need to use camera calibration matrix. And, in the website, the problem has not been solved. Th question is, how can we convert an opencv IplImage to cylindrical coordinate and display them correctly?

Thanks in advance.


问:
Determine intersection with an Ovale shape
I'm working with Java and I am trying to detect the intersection of an ovale with a rectangle.

I tough at first using Intersect would be sufficient :

```<code>Shape rect = new Rectangle2D.Double(ant.getPosX(), ant.getPosY(), 5, 5);
for (Shape obstacle : obstaclesShape) {
    if(obstacle.intersects(rect.getBounds())){
        System.out.println("Boom");
    }
}
</code>```

obstaclesShape is an ArrayList of oval shape.

```<code>Shape oval = new Ellipse2D.Double(getRandomX(), getRandomY(), obstacle.getRandomWidth(), obstacle.
this.obstaclesShape.add(oval);
</code>```

But using this method is not reliable enough. The event seems to be triggered almost randomly.

So I was asking myself wouldn't it be better to use mathematic and determine the position of the border of my ellipsis? Something which would be determine by the angle and height / width I guess.

The thing is how to determine it precisely? What is the formula for it? Or is there a better way?

答:
Yes, it is worth to apply some math and find whether your ellipse intersects rectangle.

Let rectangle has corners (x0,y0) and (x1,y1) and ellipse has center (cx, cy), horizontal semi-axis a, vertical sem-axis b.

At first we can make affine transformation to simplify calculations - we transform ellipse into origin-centered circle with radius 1. Rectangle will transform too, and intersection fact does not change.

```<code>With such transform  we apply shift by (-cx,-cy), scaling by `1/a` in OX direction and scaling by `1/b` in 0Y direction. After that rectangle will have coordinates

 xxx0 = (x0-cx) / a
 yyy0 = (y0-cy) / b
 xxx1 = (x1-cx) / a
 yyy1 = (y1-cy) / b
</code>```

Now we can apply described here approach to find a distance between origin (circle center) and  rectangle. If it less than 1, objects do intersect.

Slightly modified function (Delphi)

```<code>function RectDistanceToZeroLessThan1(RR: TRect): Boolean;
var
  wh, hh, dx, dy, t, SquaredDist: Double;
begin
  SquaredDist := 0;

  //width and height
  wh := RR.Right - RR.Left;
  hh := RR.Bottom - RR.Top;

  //doubled rectangle center coordinates
  dx :=  - (RR.Left + RR.Right);
  dy :=  - (RR.Top + RR.Bottom);

  //rectangle sides divide plane to 9 parts,
  t := dx + wh;
  if t < 0 then
    SquaredDist := t * t
  else begin
    t := dx - wh;
    if t > 0 then
      SquaredDist := t * t
  end;
  t := dy + hh;
  if t < 0 then
    SquaredDist := SquaredDist + t * t
  else begin
    t := dy - hh;
    if t > 0 then
      SquaredDist := SquaredDist + t * t
  end;

  Result = SquaredDist <= 4 // due to removed 0.5 coefficients
end;
</code>```

Body:
I'm working with Java and I am trying to detect the intersection of an ovale with a rectangle.

I tough at first using Intersect would be sufficient :

Shape rect = new Rectangle2D.Double(ant.getPosX(), ant.getPosY(), 5, 5);
for (Shape obstacle : obstaclesShape) {
    if(obstacle.intersects(rect.getBounds())){
        System.out.println("Boom");
    }
}

obstaclesShape is an ArrayList of oval shape.

Shape oval = new Ellipse2D.Double(getRandomX(), getRandomY(), obstacle.getRandomWidth(), obstacle.
this.obstaclesShape.add(oval);

But using this method is not reliable enough. The event seems to be triggered almost randomly.

So I was asking myself wouldn't it be better to use mathematic and determine the position of the border of my ellipsis? Something which would be determine by the angle and height / width I guess.

The thing is how to determine it precisely? What is the formula for it? Or is there a better way?

Body:
Yes, it is worth to apply some math and find whether your ellipse intersects rectangle.

Let rectangle has corners (x0,y0) and (x1,y1) and ellipse has center (cx, cy), horizontal semi-axis a, vertical sem-axis b.

At first we can make affine transformation to simplify calculations - we transform ellipse into origin-centered circle with radius 1. Rectangle will transform too, and intersection fact does not change.

With such transform  we apply shift by (-cx,-cy), scaling by `1/a` in OX direction and scaling by `1/b` in 0Y direction. After that rectangle will have coordinates

 xxx0 = (x0-cx) / a
 yyy0 = (y0-cy) / b
 xxx1 = (x1-cx) / a
 yyy1 = (y1-cy) / b

Now we can apply described here approach to find a distance between origin (circle center) and  rectangle. If it less than 1, objects do intersect.

Slightly modified function (Delphi)

function RectDistanceToZeroLessThan1(RR: TRect): Boolean;
var
  wh, hh, dx, dy, t, SquaredDist: Double;
begin
  SquaredDist := 0;

  //width and height
  wh := RR.Right - RR.Left;
  hh := RR.Bottom - RR.Top;

  //doubled rectangle center coordinates
  dx :=  - (RR.Left + RR.Right);
  dy :=  - (RR.Top + RR.Bottom);

  //rectangle sides divide plane to 9 parts,
  t := dx + wh;
  if t < 0 then
    SquaredDist := t * t
  else begin
    t := dx - wh;
    if t > 0 then
      SquaredDist := t * t
  end;
  t := dy + hh;
  if t < 0 then
    SquaredDist := SquaredDist + t * t
  else begin
    t := dy - hh;
    if t > 0 then
      SquaredDist := SquaredDist + t * t
  end;

  Result = SquaredDist <= 4 // due to removed 0.5 coefficients
end;


问:
Creating a script for a custom field output in ABAQUS
I want to create a custom field output in ABAQUS. For the purpose of proof on concept, I want to display the maximum shear stress as calculated from the Mohrs circle, as discussed here for a 2D shell.

I have my code below for reference:

```<code>from abaqusConstants import *
from odbAccess import *
from math import *
from copy import deepcopy
from caeModules import *
from driverUtils import executeOnCaeStartup

# ******************************************************************************
#Items in this box require student input when changing files

#must input the file path here.
odbPath = "/home/MohrsTest.odb"

odb = session.openOdb(name=odbPath, readOnly=FALSE)
odb = session.odbs[odbPath]
#this will display the instance names. Please choose one to input in line 14.
print odb.rootAssembly.instances.keys()
grout_instance = odb.rootAssembly.instances['SQUARE-1']
# ******************************************************************************
keys = odb.steps.keys()
for key in keys:
    step = odb.steps[key]
    for frame in step.frames:
        print frame.description
        Stress = frame.fieldOutputs['S']
        #try modifying scalar fields rather than creating new var element by element.
        S11=Stress.getScalarField(componentLabel="S11")
        S22=Stress.getScalarField(componentLabel="S22")
        S12=Stress.getScalarField(componentLabel="S12")
        TauMax=((S11+S22)*0.5+sqrt(power((S11-S22)/2, 2)+power(S12, 2)))-((S11+S22)*0.5-sqrt(power((S11-S22)/2, 2)+power(S12, 2)))/2
        ThetaP=(atan2(2 * S12, (S11 - S22))/2) * 180/pi
        frame.FieldOutput(name='Tau Max', description='Max Tau from Mohrs circle',field=TauMax)
        frame.FieldOutput(name='Theta P', description='Thetap as measured ccw from 0 degree',field=Thetap)
odb.save()
odb.close()
#  must re - open the output database to see the new custom field output
</code>```

Abaqus throws an error immediately upon trying to calculate TauMax because of "Type Error: A float is required." However, I tried using "Tools->Field Outputs-> Create from Fields" and then created a field output in the cae for the individual frame.
If I look at the replay file for this action, I can see the following code:

```<code>s1f1_S = session.odbs['/home/MohrsTest.odb'].steps['Step-1'].frames[1].fieldOutputs['S']
tmpField = (((s1f1_S.getScalarField(componentLabel="S11")+\
    s1f1_S.getScalarField(componentLabel="S22"))*0.5+sqrt(power((
    s1f1_S.getScalarField(componentLabel="S11")-s1f1_S.getScalarField(
    componentLabel="S22"))/2, 2)+power(s1f1_S.getScalarField(
    componentLabel="S12"), 2)))-((s1f1_S.getScalarField(componentLabel="S11")+\
    s1f1_S.getScalarField(componentLabel="S22"))*0.5-sqrt(power((
    s1f1_S.getScalarField(componentLabel="S11")-s1f1_S.getScalarField(
    componentLabel="S22"))/2, 2)+power(s1f1_S.getScalarField(
    componentLabel="S12"), 2))))/2
</code>```

Thus, clearly math operations on a FieldObject must be possible. Why does my code not permit this?

I am happy to provide all .odb and .cae files for reference and verification.

答: I'm pretty sure native Abaqus/CAE scripts use numpy for math functions.  But numpy.sqrt gets overwritten by math.sqrt when you do from math import *.  math.sqrt can't handle the numpy array generated by .getScalarField(), and you get an error.

Body:
I want to create a custom field output in ABAQUS. For the purpose of proof on concept, I want to display the maximum shear stress as calculated from the Mohrs circle, as discussed here for a 2D shell.

I have my code below for reference:

from abaqusConstants import *
from odbAccess import *
from math import *
from copy import deepcopy
from caeModules import *
from driverUtils import executeOnCaeStartup

# ******************************************************************************
#Items in this box require student input when changing files

#must input the file path here.
odbPath = "/home/MohrsTest.odb"

odb = session.openOdb(name=odbPath, readOnly=FALSE)
odb = session.odbs[odbPath]
#this will display the instance names. Please choose one to input in line 14.
print odb.rootAssembly.instances.keys()
grout_instance = odb.rootAssembly.instances['SQUARE-1']
# ******************************************************************************
keys = odb.steps.keys()
for key in keys:
    step = odb.steps[key]
    for frame in step.frames:
        print frame.description
        Stress = frame.fieldOutputs['S']
        #try modifying scalar fields rather than creating new var element by element.
        S11=Stress.getScalarField(componentLabel="S11")
        S22=Stress.getScalarField(componentLabel="S22")
        S12=Stress.getScalarField(componentLabel="S12")
        TauMax=((S11+S22)*0.5+sqrt(power((S11-S22)/2, 2)+power(S12, 2)))-((S11+S22)*0.5-sqrt(power((S11-S22)/2, 2)+power(S12, 2)))/2
        ThetaP=(atan2(2 * S12, (S11 - S22))/2) * 180/pi
        frame.FieldOutput(name='Tau Max', description='Max Tau from Mohrs circle',field=TauMax)
        frame.FieldOutput(name='Theta P', description='Thetap as measured ccw from 0 degree',field=Thetap)
odb.save()
odb.close()
#  must re - open the output database to see the new custom field output

Abaqus throws an error immediately upon trying to calculate TauMax because of "Type Error: A float is required." However, I tried using "Tools->Field Outputs-> Create from Fields" and then created a field output in the cae for the individual frame.
If I look at the replay file for this action, I can see the following code:

s1f1_S = session.odbs['/home/MohrsTest.odb'].steps['Step-1'].frames[1].fieldOutputs['S']
tmpField = (((s1f1_S.getScalarField(componentLabel="S11")+\
    s1f1_S.getScalarField(componentLabel="S22"))*0.5+sqrt(power((
    s1f1_S.getScalarField(componentLabel="S11")-s1f1_S.getScalarField(
    componentLabel="S22"))/2, 2)+power(s1f1_S.getScalarField(
    componentLabel="S12"), 2)))-((s1f1_S.getScalarField(componentLabel="S11")+\
    s1f1_S.getScalarField(componentLabel="S22"))*0.5-sqrt(power((
    s1f1_S.getScalarField(componentLabel="S11")-s1f1_S.getScalarField(
    componentLabel="S22"))/2, 2)+power(s1f1_S.getScalarField(
    componentLabel="S12"), 2))))/2

Thus, clearly math operations on a FieldObject must be possible. Why does my code not permit this?

I am happy to provide all .odb and .cae files for reference and verification.


问:
HTML Javascript font size change
```<code><html>
<head>
  <meta charset="utf-8">
  <script>
    function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;
      document.write("name="+name+"");
      document.write("&snumber="+snumber+"<br />");
    }
  </script>
</head>

<body>
   <h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">
</body>
</html>
</code>```

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

```<code> <h2></h2>
</code>```

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

答:
```<code>    var name = document.getElementById('name').value;
    name= "<span style='font-size:32px;'>"+name+"</span>";
    snumber= "<span style='font-size:32px;'>"+snumber+"</span>";
    var snumber = document.getElementById('snumber').value;
    document.write("name="+name+"");
    document.write("&snumber="+snumber+"<br />");
</code>```

Title: HTML Javascript font size change

Body:
  <meta charset="utf-8">

Example of sending data using POST

     Name :
   <input type="text" id="name">

     Student number:
   <input type="text" id="snumber">

   <input type="button" value="submit" onclick="test();">

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!


问:
Postgres 9.6 function performing poorly compared to straight sql
I have this function, and it works, it gives the most recent b record.

```<code>create or replace function most_recent_b(the_a a) returns b as $$
    select distinct on (c.a_id) b.*
    from c
    join b on b.c_id = c.id
    where c.a_id = the_a.id
    order by c.a_id, b.date desc
$$ language sql stable;
</code>```

This runs ~5000ms with real data. V.S. the following which runs in 500ms

```<code>create or replace function most_recent_b(the_a a) returns b as $$
    select distinct on (c.a_id) b.*
    from c
    join b on b.c_id = c.id
    where c.a_id = 1347
    order by c.a_id, b.date desc
$$ language sql stable;
</code>```

The only difference being that I've hard coded a.id with a value 1347 instead of using its param value.

Also running this query without a function  also gives me speeds around 500ms

I'm running PostgreSQL 9.6, so the query planner failing in functions results I see suggested elsewhere shouldn't apply to me right?

I'm sure its not the query itself that is the issue, as this is my third iteration at it, different techniques to get this result all result in the same slow down when inside a function.

As requested by @laurenz-albe

Result of EXPLAIN (ANALYZE, BUFFERS) with constant

```<code>Unique  (cost=60.88..60.89 rows=3 width=463) (actual time=520.117..520.122 rows=1 loops=1)
  Buffers: shared hit=14555
  ->  Sort  (cost=60.88..60.89 rows=3 width=463) (actual time=520.116..520.120 rows=9 loops=1)
        Sort Key: b.date DESC
        Sort Method: quicksort  Memory: 28kB
        Buffers: shared hit=14555
        ->  Hash Join  (cost=13.71..60.86 rows=3 width=463) (actual time=386.848..520.083 rows=9 loops=1)
              Hash Cond: (b.c_id = c.id)
              Buffers: shared hit=14555
              ->  Seq Scan on b (cost=0.00..46.38 rows=54 width=459) (actual time=25.362..519.140 rows=51 loops=1)
                    Filter: b_can_view(b.*)
                    Rows Removed by Filter: 112
                    Buffers: shared hit=14530
              ->  Hash  (cost=13.67..13.67 rows=3 width=8) (actual time=0.880..0.880 rows=10 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=25
                    ->  Subquery Scan on c  (cost=4.21..13.67 rows=3 width=8) (actual time=0.222..0.872 rows=10 loops=1)
                          Buffers: shared hit=25
                          ->  Bitmap Heap Scan on c c_1  (cost=4.21..13.64 rows=3 width=2276) (actual time=0.221..0.863 rows=10 loops=1)
                                Recheck Cond: (a_id = 1347)
                                Filter: c_can_view(c_1.*)
                                Heap Blocks: exact=4
                                Buffers: shared hit=25
                                ->  Bitmap Index Scan on c_a_id_c_number_idx  (cost=0.00..4.20 rows=8 width=0) (actual time=0.007..0.007 rows=10 loops=1)
                                      Index Cond: (a_id = 1347)
                                      Buffers: shared hit=1
Execution time: 520.256 ms
</code>```

And this is the result after running six times with the parameter being passed ( it was exactly six times as you predicted :) )

Slow query;

```<code>Unique  (cost=57.07..57.07 rows=1 width=463) (actual time=5040.237..5040.243 rows=1 loops=1)
  Buffers: shared hit=145325
  ->  Sort  (cost=57.07..57.07 rows=1 width=463) (actual time=5040.237..5040.240 rows=9 loops=1)
        Sort Key: b.date DESC
        Sort Method: quicksort  Memory: 28kB
        Buffers: shared hit=145325
        ->  Nested Loop  (cost=0.14..57.06 rows=1 width=463) (actual time=912.354..5040.195 rows=9 loops=1)
              Join Filter: (c.id = b.c_id)
              Rows Removed by Join Filter: 501
              Buffers: shared hit=145325
              ->  Index Scan using c_a_id_idx on c (cost=0.14..9.45 rows=1 width=2276) (actual time=0.378..1.171 rows=10 loops=1)
                    Index Cond: (a_id = $1)
                    Filter: c_can_view(c.*)
                    Buffers: shared hit=25
              ->  Seq Scan on b (cost=0.00..46.38 rows=54 width=459) (actual time=24.842..503.854 rows=51 loops=10)
                    Filter: b_can_view(b.*)
                    Rows Removed by Filter: 112
                    Buffers: shared hit=145300
Execution time: 5040.375 ms
</code>```

Its worth noting that I have some strict row level security involved, and I suspect this is why these queries are both slow, however, one is 10 times slower than the other.

I've changed my original table names hopefully my search and replace was good here.

答:
The expensive part of your query execution is the filter b_can_view(b.*), which must come from your row level security definition.

The fast execution:

```<code>Seq Scan on b (cost=0.00..46.38 rows=54 width=459)
              (actual time=25.362..519.140 rows=51 loops=1)
  Filter: b_can_view(b.*)
  Rows Removed by Filter: 112
  Buffers: shared hit=14530
</code>```

The slow execution:

```<code>Seq Scan on b (cost=0.00..46.38 rows=54 width=459)
              (actual time=24.842..503.854 rows=51 loops=10)
  Filter: b_can_view(b.*)
  Rows Removed by Filter: 112
  Buffers: shared hit=145300
</code>```

The difference is that the scan is executed 10 times in the slow case (loops=10) and touches 10 times as many data blocks.

When using the generic plan, PostgreSQL underestimates how many rows in c will satisfy the condition c.a_id = $1, because it doesn't know that the actual value is 1347, which is more frequent than average.

Since PostgreSQL thinks there will be at most one row from c, it chooses a nested loop join with a sequential scan of b on the inner side.

Now two problems combine:

Calling function b_can_view takes over 3 milliseconds per row (which PostgreSQL doesn't know), which accounts for the half second that a sequential scan of the 163 rows takes.

There are actually 10 rows found in c instead of the predicted 1, so table b is scanned 10 times, and you end up with a query duration of 5 seconds.

So what can you do?

Tell PostgreSQL how expensive the b_can_view is. Use ALTER TABLE to set the COST for that function to 1000 or 10000 to reflect reality. That alone will not be enough to get a faster plan, since PostgreSQL thinks that it has to execute a single sequential scan anyway, but it is a good thing to give the optimizer correct data.

Create an index on b(c_id). That will enable PostgreSQL to avoid a sequential scan of b, which it will try to do once it is aware how expensive the function is.

Also, try to make the function b_can_view cheaper. That will make your experience so much better.

Body:
I have this function, and it works, it gives the most recent b record.

create or replace function most_recent_b(the_a a) returns b as $$
    select distinct on (c.a_id) b.*
    from c
    join b on b.c_id = c.id
    where c.a_id = the_a.id
    order by c.a_id, b.date desc
$$ language sql stable;

This runs ~5000ms with real data. V.S. the following which runs in 500ms

create or replace function most_recent_b(the_a a) returns b as $$
    select distinct on (c.a_id) b.*
    from c
    join b on b.c_id = c.id
    where c.a_id = 1347
    order by c.a_id, b.date desc
$$ language sql stable;

The only difference being that I've hard coded a.id with a value 1347 instead of using its param value.

Also running this query without a function  also gives me speeds around 500ms

I'm running PostgreSQL 9.6, so the query planner failing in functions results I see suggested elsewhere shouldn't apply to me right?

I'm sure its not the query itself that is the issue, as this is my third iteration at it, different techniques to get this result all result in the same slow down when inside a function.

As requested by @laurenz-albe

Result of EXPLAIN (ANALYZE, BUFFERS) with constant

Unique  (cost=60.88..60.89 rows=3 width=463) (actual time=520.117..520.122 rows=1 loops=1)
  Buffers: shared hit=14555
  ->  Sort  (cost=60.88..60.89 rows=3 width=463) (actual time=520.116..520.120 rows=9 loops=1)
        Sort Key: b.date DESC
        Sort Method: quicksort  Memory: 28kB
        Buffers: shared hit=14555
        ->  Hash Join  (cost=13.71..60.86 rows=3 width=463) (actual time=386.848..520.083 rows=9 loops=1)
              Hash Cond: (b.c_id = c.id)
              Buffers: shared hit=14555
              ->  Seq Scan on b (cost=0.00..46.38 rows=54 width=459) (actual time=25.362..519.140 rows=51 loops=1)
                    Filter: b_can_view(b.*)
                    Rows Removed by Filter: 112
                    Buffers: shared hit=14530
              ->  Hash  (cost=13.67..13.67 rows=3 width=8) (actual time=0.880..0.880 rows=10 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=25
                    ->  Subquery Scan on c  (cost=4.21..13.67 rows=3 width=8) (actual time=0.222..0.872 rows=10 loops=1)
                          Buffers: shared hit=25
                          ->  Bitmap Heap Scan on c c_1  (cost=4.21..13.64 rows=3 width=2276) (actual time=0.221..0.863 rows=10 loops=1)
                                Recheck Cond: (a_id = 1347)
                                Filter: c_can_view(c_1.*)
                                Heap Blocks: exact=4
                                Buffers: shared hit=25
                                ->  Bitmap Index Scan on c_a_id_c_number_idx  (cost=0.00..4.20 rows=8 width=0) (actual time=0.007..0.007 rows=10 loops=1)
                                      Index Cond: (a_id = 1347)
                                      Buffers: shared hit=1
Execution time: 520.256 ms

And this is the result after running six times with the parameter being passed ( it was exactly six times as you predicted :) )

Slow query;

Unique  (cost=57.07..57.07 rows=1 width=463) (actual time=5040.237..5040.243 rows=1 loops=1)
  Buffers: shared hit=145325
  ->  Sort  (cost=57.07..57.07 rows=1 width=463) (actual time=5040.237..5040.240 rows=9 loops=1)
        Sort Key: b.date DESC
        Sort Method: quicksort  Memory: 28kB
        Buffers: shared hit=145325
        ->  Nested Loop  (cost=0.14..57.06 rows=1 width=463) (actual time=912.354..5040.195 rows=9 loops=1)
              Join Filter: (c.id = b.c_id)
              Rows Removed by Join Filter: 501
              Buffers: shared hit=145325
              ->  Index Scan using c_a_id_idx on c (cost=0.14..9.45 rows=1 width=2276) (actual time=0.378..1.171 rows=10 loops=1)
                    Index Cond: (a_id = $1)
                    Filter: c_can_view(c.*)
                    Buffers: shared hit=25
              ->  Seq Scan on b (cost=0.00..46.38 rows=54 width=459) (actual time=24.842..503.854 rows=51 loops=10)
                    Filter: b_can_view(b.*)
                    Rows Removed by Filter: 112
                    Buffers: shared hit=145300
Execution time: 5040.375 ms

Its worth noting that I have some strict row level security involved, and I suspect this is why these queries are both slow, however, one is 10 times slower than the other.

I've changed my original table names hopefully my search and replace was good here.

Body:
The expensive part of your query execution is the filter b_can_view(b.*), which must come from your row level security definition.

The fast execution:

Seq Scan on b (cost=0.00..46.38 rows=54 width=459)
              (actual time=25.362..519.140 rows=51 loops=1)
  Filter: b_can_view(b.*)
  Rows Removed by Filter: 112
  Buffers: shared hit=14530

The slow execution:

Seq Scan on b (cost=0.00..46.38 rows=54 width=459)
              (actual time=24.842..503.854 rows=51 loops=10)
  Filter: b_can_view(b.*)
  Rows Removed by Filter: 112
  Buffers: shared hit=145300

The difference is that the scan is executed 10 times in the slow case (loops=10) and touches 10 times as many data blocks.

When using the generic plan, PostgreSQL underestimates how many rows in c will satisfy the condition c.a_id = $1, because it doesn't know that the actual value is 1347, which is more frequent than average.

Since PostgreSQL thinks there will be at most one row from c, it chooses a nested loop join with a sequential scan of b on the inner side.

Now two problems combine:

Calling function b_can_view takes over 3 milliseconds per row (which PostgreSQL doesn't know), which accounts for the half second that a sequential scan of the 163 rows takes.

There are actually 10 rows found in c instead of the predicted 1, so table b is scanned 10 times, and you end up with a query duration of 5 seconds.

So what can you do?

Tell PostgreSQL how expensive the b_can_view is. Use ALTER TABLE to set the COST for that function to 1000 or 10000 to reflect reality. That alone will not be enough to get a faster plan, since PostgreSQL thinks that it has to execute a single sequential scan anyway, but it is a good thing to give the optimizer correct data.

Create an index on b(c_id). That will enable PostgreSQL to avoid a sequential scan of b, which it will try to do once it is aware how expensive the function is.

Also, try to make the function b_can_view cheaper. That will make your experience so much better.


问:
CKEditor (in a SPA) freezes when navigating back to the editor page
I'm trying to integrate CKEditor in a page of a SPA (Single Page Application).

CKEditor behaves correctly within the SPA page on the first visit, but not on next visits. For example, when pressing the backward browser arrow (to display the previous SPA page) and then the forward arrow (to display again the SPA page with CKEditor), CKEditor appears but the content has been erased and it's not reacting anymore. There is no carret when cliking on the text area. Also all API calls (such as setData() or resize()) have no effect anymore (whereas they were working on fist visit).

I presume CKEditor doesn't like its element to be removed from the DOM (that's what happens when switching to another page) and then be re-added to the DOM (that's what happens when visiting the page again).

EDIT ON July 5 2017

Thanks for your proposition to destroy CKEditor when leaving the page and to recreate it when navigating back, but this causes the lost of the editor state such as the the scrollbar position, the caret position, text selection, etc...

Ideally I would like to make it possible for a user to visit another page while he is in the middle of writing something in the editor (for example to check an information or copy a content from another page) and then to continue exactly where he was (no change on scrollbar, caret, selection,...) when he navigates back to the editor.

Is is possible?

答:
Removing CKEditor just by removing its parent container like in your fiddle is not a good solution as CKEditor attaches some listeners to the DOM and by removing the container you are detaching those listeners which are not reattached then.

You should destroy the editor before removing from DOM and then recreate it. Remember that destroying happens in an async manner so to know when it is finished you may listen to destroy event.

Here is modified fiddle using destroy method (without handling destroy event which should be added).

EDIT ON July 10 2017

To preserve the state of the editor (scrollbar position, text selection, etc) between destroy - recreate, state of all this elements should be retained before destroying editor and then set after recreating it. It is doable, but requires some work and quite a lot of custom code.

Ideally I would like to make it possible for a user to visit another page while he is in the middle of writing something in the editor

Since you are creating a SPA application, for the above the better solution will be to use some floating/fixed container in which CKEditor is placed and which does not reload with rest of the page upon navigation (e.g. the same as Facebook chat works).

Also remember that recreating CKEditor takes some time (very short, but it may be still visible) so on every page navigation it will be visible for the user that something is happening with the editor even though its state does not changed.


问:
SQL data retrieve - C#
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ.
For example, 1st time i want 5rd row,then 2nd, then 9...so on.

I searched it through the internet. I got only two answers.

Use several SqlConnection objects.

reader= sqlCommand.ExecuteReader();
While(reader.Read()){
    reader["Column Name"].ToString();
}

If you got my problem, please help me
Thank you.

答:
Two ways, that I see:

1) Get all rows in one sql statement, then access the row you need in memory.

Or (of "everything" is too much or you need recent data)

2) Get only the specific row you need, and again for the next row.

Title: SQL data retrieve - C#


问:
Date.parse() not working with highchart
I use HIGHCHART in angularjs app.
I get from API date

```<code>var dateTime = new Date(value.date_time); // Wed Jun 07 2017 10:00:00 GMT+0200 (Central European Summer Time)
</code>```

after I convert to unixTimeStamp

```<code>var unixTimeStamp1 = dateTime.getTime(); // 1496822400000
</code>```

And this working normally in google chrome and firefox when opening highchart, but in Safari and IE not working. Now I need to convert to milliseconds

```<code>var unixTimeStamp = Date.parse(unixTimeStamp1); // here i get NaN
</code>```

and all charts is empty.

If I try this instead of above

```<code>var unixTimeStamp = new Date(unixTimeStamp1*1000); // Wed May 24 49476 06:00:00 GMT+0200 (Central European Summer Time)
</code>```

this work in all browser (IE, Safari, Chrome, Firefox...) but, date in the chart is not correct.
With this, I get date like this on image bellow

this is the correct date

My apologies if this is a duplicate question, but I didn't find the correct answer for my problem.

答:
You cannot use Date.parse to parse that string and be sure that it works on every browser - see the description of Date.parse:

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

If your date has the format like yyyy-mm-dd hh:mm:ss, you can parse it like this:

```<code>const date = '2017-06-07 10:00:00'
const d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
const parsed = new Date(d[1], d[2], d[3], d[4], d[5], d[6]).getTime()
</code>```

example: http://jsfiddle.net/zt1k31sf/

Title: Date.parse() not working with highchart

Body:
I use HIGHCHART in angularjs app.
I get from API date

var dateTime = new Date(value.date_time); // Wed Jun 07 2017 10:00:00 GMT+0200 (Central European Summer Time)

after I convert to unixTimeStamp

var unixTimeStamp1 = dateTime.getTime(); // 1496822400000

And this working normally in google chrome and firefox when opening highchart, but in Safari and IE not working. Now I need to convert to milliseconds

var unixTimeStamp = Date.parse(unixTimeStamp1); // here i get NaN

and all charts is empty.

If I try this instead of above

var unixTimeStamp = new Date(unixTimeStamp1*1000); // Wed May 24 49476 06:00:00 GMT+0200 (Central European Summer Time)

this work in all browser (IE, Safari, Chrome, Firefox...) but, date in the chart is not correct.
With this, I get date like this on image bellow

this is the correct date

My apologies if this is a duplicate question, but I didn't find the correct answer for my problem.

Body:
You cannot use Date.parse to parse that string and be sure that it works on every browser - see the description of Date.parse:

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

If your date has the format like yyyy-mm-dd hh:mm:ss, you can parse it like this:

const date = '2017-06-07 10:00:00'
const d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
const parsed = new Date(d[1], d[2], d[3], d[4], d[5], d[6]).getTime()

example: http://jsfiddle.net/zt1k31sf/


问:
what's the meaning of @aar with transitive = true
i use crashlytics only as an example.

what's is the difference from

```<code>    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') { transitive = true; }
</code>```

and

```<code>    compile 'com.crashlytics.sdk.android:crashlytics:2.6.8'
</code>```

答:
If you use the ...@artifacttype notation in a Gradle dependency it means "only get me this artifact and no transitive dependencies". By additionally setting transitive = true, you are fetching the transitive dependencies despite that fact.

The first version gets the aar with dependencies and as far as I remember the second always gets the jar if one is present and else nothing but the dependencies. Add configurations.compile.each { println it } to output the actual files in the configuration and you should see the difference.

In the case of crashlytics there is no difference:

```<code>compile 'com.crashlytics.sdk.android:crashlytics:2.6.8'
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics/2.6.8/2f667ae0609d82045cbe602d38df3fbf2c9528dd/crashlytics-2.6.8.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/beta/1.2.5/f73d30657bb44ecb79d434a4ae3fb7d887371d84/beta-1.2.5.aar
/home/xan/.gradle/caches/modules-2/files-2.1/io.fabric.sdk.android/fabric/1.3.17/85fc9aae9009f6fb2beaf23fa0ce1ae13f124413/fabric-1.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics-core/2.3.17/f3bed4c297be8d30dc5aa7f18b06dff75435bde4/crashlytics-core-2.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/answers/1.3.13/83dc1dd439c7da04ce9705f18037fe7551ae06bc/answers-1.3.13.aar

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') { transitive = true; }
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics/2.6.8/2f667ae0609d82045cbe602d38df3fbf2c9528dd/crashlytics-2.6.8.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/beta/1.2.5/f73d30657bb44ecb79d434a4ae3fb7d887371d84/beta-1.2.5.aar
/home/xan/.gradle/caches/modules-2/files-2.1/io.fabric.sdk.android/fabric/1.3.17/85fc9aae9009f6fb2beaf23fa0ce1ae13f124413/fabric-1.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics-core/2.3.17/f3bed4c297be8d30dc5aa7f18b06dff75435bde4/crashlytics-core-2.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/answers/1.3.13/83dc1dd439c7da04ce9705f18037fe7551ae06bc/answers-1.3.13.aar
</code>```

Body:
i use crashlytics only as an example.

what's is the difference from

    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') { transitive = true; }

and

    compile 'com.crashlytics.sdk.android:crashlytics:2.6.8'

Body:
If you use the ...@artifacttype notation in a Gradle dependency it means "only get me this artifact and no transitive dependencies". By additionally setting transitive = true, you are fetching the transitive dependencies despite that fact.

The first version gets the aar with dependencies and as far as I remember the second always gets the jar if one is present and else nothing but the dependencies. Add configurations.compile.each { println it } to output the actual files in the configuration and you should see the difference.

In the case of crashlytics there is no difference:

compile 'com.crashlytics.sdk.android:crashlytics:2.6.8'
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics/2.6.8/2f667ae0609d82045cbe602d38df3fbf2c9528dd/crashlytics-2.6.8.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/beta/1.2.5/f73d30657bb44ecb79d434a4ae3fb7d887371d84/beta-1.2.5.aar
/home/xan/.gradle/caches/modules-2/files-2.1/io.fabric.sdk.android/fabric/1.3.17/85fc9aae9009f6fb2beaf23fa0ce1ae13f124413/fabric-1.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics-core/2.3.17/f3bed4c297be8d30dc5aa7f18b06dff75435bde4/crashlytics-core-2.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/answers/1.3.13/83dc1dd439c7da04ce9705f18037fe7551ae06bc/answers-1.3.13.aar

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') { transitive = true; }
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics/2.6.8/2f667ae0609d82045cbe602d38df3fbf2c9528dd/crashlytics-2.6.8.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/beta/1.2.5/f73d30657bb44ecb79d434a4ae3fb7d887371d84/beta-1.2.5.aar
/home/xan/.gradle/caches/modules-2/files-2.1/io.fabric.sdk.android/fabric/1.3.17/85fc9aae9009f6fb2beaf23fa0ce1ae13f124413/fabric-1.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/crashlytics-core/2.3.17/f3bed4c297be8d30dc5aa7f18b06dff75435bde4/crashlytics-core-2.3.17.aar
/home/xan/.gradle/caches/modules-2/files-2.1/com.crashlytics.sdk.android/answers/1.3.13/83dc1dd439c7da04ce9705f18037fe7551ae06bc/answers-1.3.13.aar


问:
Styling HTML Dropdown List
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

```<code>(+43) Austria
(+353) Ireland
(+1) United States
</code>```

Would become:

```<code>(+43)  Austria
(+353) Ireland
(+1)   United States
</code>```

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

```<code>    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>
</code>```

答:
You can simply use nbsp; to format text inside the <option> as we cannot have any other HTML element inside <option> and apply css to that elements and get intended result.

 <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61)      Australia</option>
    <option value="+43">(+43)      Austria</option>
    <option value="+32">(+32)      Belgium</option>
    <option value="+55">(+55)      Brazil</option>
    <option value="+1">(+1)        Canada</option>
    <option value="+33">(+33)      France</option>
    <option value="+49">(+49)      Germany</option>
    <option value="+353">(+353)    Ireland</option>
    <option value="+39">(+39)      Italy</option>
    <option value="+31">(+31)      Netherlands </option>
    <option value="+64">(+64)      New Zealand</option>
    <option value="+48">(+48)      Poland</option>
    <option value="+351">(+351)    Portugal</option>
    <option value="+27">(+27)      South Africa</option>
    <option value="+34">(+34)      Spain</option>
    <option value="+41">(+41)      Switzerland</option>
    <option selected="selected" value="+44">(+44)      United Kingdom</option>
    <option value="+1">(+1)        United States</option>
    </select>```

Title: Styling HTML Dropdown List

Body:
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

(+43) Austria
(+353) Ireland
(+1) United States

Would become:

(+43)  Austria
(+353) Ireland
(+1)   United States

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>

Body:
You can simply use nbsp; to format text inside the <option> as we cannot have any other HTML element inside <option> and apply css to that elements and get intended result.

 <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Australia</option>
    <option value="+43">(+43)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Austria</option>
    <option value="+32">(+32)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Belgium</option>
    <option value="+55">(+55)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Brazil</option>
    <option value="+1">(+1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Canada</option>
    <option value="+33">(+33)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; France</option>
    <option value="+49">(+49)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Germany</option>
    <option value="+353">(+353)&nbsp;&nbsp;&nbsp; Ireland</option>
    <option value="+39">(+39)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Italy</option>
    <option value="+31">(+31)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Netherlands </option>
    <option value="+64">(+64)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; New Zealand</option>
    <option value="+48">(+48)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Poland</option>
    <option value="+351">(+351)&nbsp;&nbsp;&nbsp; Portugal</option>
    <option value="+27">(+27)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; South Africa</option>
    <option value="+34">(+34) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Spain</option>
    <option value="+41">(+41)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Switzerland</option>
    <option selected="selected" value="+44">(+44)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; United Kingdom</option>
    <option value="+1">(+1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;United States</option>
    </select>


问:
Label prediction to probability score prediction/AUC using scikit-learn SVM
For a DS competition I was using SVM to do binary classification. Here tdata,vdata both have 256 features. tlabels,vlabels both have dimensions n_samples x 1 and their unique values are 0/1.

Now, as per the competition rules, in place of labels, we need to submit probability score(between 0 to 1) and AUC will be used to decide the ranking.

I am pretty new to SVMs and Sklearn. Any pointers on how to convert this code to generate probability scores and AUC, will be of great help.

Code:

```<code>classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced')
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
cm = metrics.confusion_matrix(expected, predicted)
accuracy = (cm[0,0]+cm[1,1])*100.0/sum(sum(cm))
print("accuracy = "+str(accuracy))
</code>```

Output:

```<code>Classification report for classifier SVC(C=1.0, cache_size=200, class_weight='balanced', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.00020000000000000001,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False):
             precision    recall  f1-score   support

        0.0       0.93      0.88      0.90      1881
        1.0       0.92      0.95      0.94      2686

avg / total       0.92      0.92      0.92      4567

accuracy = 92.3144296037
</code>```

答:
Step 1

Define: probability=True in SVC (this parameter is available for SVC) see link.

```<code>classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced', probability=True)
</code>```

Step 2

Then you need to use predict_proba method.

Example:

```<code>classifier.fit(X,y)
classifier.predict_proba(X)
</code>```

The result is the probabilities that you want in range [0,1].

Hope this helps.

SVC link

predict_proba

Body:
For a DS competition I was using SVM to do binary classification. Here tdata,vdata both have 256 features. tlabels,vlabels both have dimensions n_samples x 1 and their unique values are 0/1.

Now, as per the competition rules, in place of labels, we need to submit probability score(between 0 to 1) and AUC will be used to decide the ranking.

I am pretty new to SVMs and Sklearn. Any pointers on how to convert this code to generate probability scores and AUC, will be of great help.

Code:

classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced')
classifier.fit(tdata, tlabels)
expected = vlabels
predicted = classifier.predict(vdata)

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
cm = metrics.confusion_matrix(expected, predicted)
accuracy = (cm[0,0]+cm[1,1])*100.0/sum(sum(cm))
print("accuracy = "+str(accuracy))

Output:

Classification report for classifier SVC(C=1.0, cache_size=200, class_weight='balanced', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.00020000000000000001,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False):
             precision    recall  f1-score   support

        0.0       0.93      0.88      0.90      1881
        1.0       0.92      0.95      0.94      2686

avg / total       0.92      0.92      0.92      4567

accuracy = 92.3144296037

Body:
Step 1

Define: probability=True in SVC (this parameter is available for SVC) see link.

classifier=svm.SVC(gamma=g,C=c,kernel='rbf',class_weight='balanced', probability=True)

Step 2

Then you need to use predict_proba method.

Example:

classifier.fit(X,y)
classifier.predict_proba(X)

The result is the probabilities that you want in range [0,1].

Hope this helps.

SVC link

predict_proba


问:
Batch - Count string appearance between two patterns
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

```<code>(
echo a
echo b
echo c
)
echo z
</code>```

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

```<code>for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1
</code>```

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses

答:
Your specifications are incomplete because, as stated, this problem can be reduced to: Count the number of lines between left paren and right paren:

```<code>@echo off
setlocal

set "open="
for /F "delims=:" %%a in ('findstr /N "( )" test.txt') do (
   if not defined open (
      set "open=%%a"
   ) else (
      set /A count=%%a-open-1
   )
)
echo %count%
</code>```

Body:
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

(
echo a
echo b
echo c
)
echo z

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses

Body:
Your specifications are incomplete because, as stated, this problem can be reduced to: Count the number of lines between left paren and right paren:

@echo off
setlocal

set "open="
for /F "delims=:" %%a in ('findstr /N "( )" test.txt') do (
   if not defined open (
      set "open=%%a"
   ) else (
      set /A count=%%a-open-1
   )
)
echo %count%


问:
How to extract chats from API response with Ionic 2 rest API
I have an http API returning data in this format.

{
   "conversations":[
      [
         {
            "_id":"59563b3a5ab1af1f04d0bf52",
            "updatedAt":"2017-06-30T11:51:22.808Z",
            "createdAt":"2017-06-30T11:51:22.808Z",
            "conversationId":"59563b3a5ab1af1f04d0bf51",
            "body":"Hello Tom",
            "author":{
               "_id":"595603e325a2b014e07c69cf",
               "profile":{
                  "firstName":"Paul",
                  "lastName":"Obunga"
               }
            },
            "__v":0
         }
      ],
      [
         {
            "_id":"5956462c5ab1af1f04d0bf54",
            "updatedAt":"2017-06-30T12:38:04.469Z",
            "createdAt":"2017-06-30T12:38:04.469Z",
            "conversationId":"5956462c5ab1af1f04d0bf53",
            "body":"Hello Tomusange",
            "author":{
               "_id":"595603e325a2b014e07c69cf",
               "profile":{
                  "firstName":"Paul",
                  "lastName":"Obunga"
               }
            },
            "__v":0
         }
      ]
   ]
}```
</div>
</div>
</p>

<p>Am trying to create a simple http provider in Ionic 2 to return the message body of each conversation and the first and lastname but not really getting through.</p>

<p>Here is my Message Service extract</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>fetchConversations() {
  return new Promise((reslove, reject) => {
    let headers = new Headers();
    headers.append('Authorization', '');
    this.http.post('https://localhost:3000/api/chats', {
        headers: headers
      })
      .subscribe(res => {
        let data = res.json();
        let conversations = data.conversations;

        resolve(conversations);
      }, (err) => {
        reject(err);
      });
  })
}</code>```

Then in my ConversationListPage.

this.restProvider.fetchConversations()
  .then((result) => {
      console.log(result);
    });```

答:
```<code> <ion-list>
      <ion-item *ngFor="let item of result | async">
    {{item.author.profile.firstname + ' ' + item.author.profile.lastname + ': ' + item.body}}
      </ion-item>
  </ion-list>
</code>```

Something like this?

Body:
I have an http API returning data in this format.

{
   "conversations":[
      [
         {
            "_id":"59563b3a5ab1af1f04d0bf52",
            "updatedAt":"2017-06-30T11:51:22.808Z",
            "createdAt":"2017-06-30T11:51:22.808Z",
            "conversationId":"59563b3a5ab1af1f04d0bf51",
            "body":"Hello Tom",
            "author":{
               "_id":"595603e325a2b014e07c69cf",
               "profile":{
                  "firstName":"Paul",
                  "lastName":"Obunga"
               }
            },
            "__v":0
         }
      ],
      [
         {
            "_id":"5956462c5ab1af1f04d0bf54",
            "updatedAt":"2017-06-30T12:38:04.469Z",
            "createdAt":"2017-06-30T12:38:04.469Z",
            "conversationId":"5956462c5ab1af1f04d0bf53",
            "body":"Hello Tomusange",
            "author":{
               "_id":"595603e325a2b014e07c69cf",
               "profile":{
                  "firstName":"Paul",
                  "lastName":"Obunga"
               }
            },
            "__v":0
         }
      ]
   ]
}

Am trying to create a simple http provider in Ionic 2 to return the message body of each conversation and the first and lastname but not really getting through.

Here is my Message Service extract

fetchConversations() {
  return new Promise((reslove, reject) => {
    let headers = new Headers();
    headers.append('Authorization', '');
    this.http.post('https://localhost:3000/api/chats', {
        headers: headers
      })
      .subscribe(res => {
        let data = res.json();
        let conversations = data.conversations;

        resolve(conversations);
      }, (err) => {
        reject(err);
      });
  })
}

Then in my ConversationListPage.

this.restProvider.fetchConversations()
  .then((result) => {
      console.log(result);
    });

Body:
 <ion-list>
      <ion-item *ngFor="let item of result | async">
    {{item.author.profile.firstname + ' ' + item.author.profile.lastname + ': ' + item.body}}
      </ion-item>
  </ion-list>

Something like this?


问:
How to change --header 'Accept: application/json' to --header 'Accept: application/xml'
WSO2 API manger how to change --header 'Accept: application/json' to --header 'Accept: application/xml'?

I have added some APIs to WSO2 API Publisher. I can connect via API Console for some API but some failed. I noticed the one failing due to --header Accept: application/json'- all other which connected successfully has --header 'Accept: application/xml.

Also it keep return Response Code 0 with Response Headers:

"error": "no response from server"

I have tried to update this but still the same: /opt/wso2am-2.1.0/repository/deployment/server/synapse-configs/default/sequences/_auth_failure_handler_.xml

Please advise.

答:
In the publisher where you define the resources for your API, you can specify the "Produces" field (set it to application/xml), that should be used as the default value from the API Store test console.

Regardless that - the client could post any Accept header in the request. The "Produces" field is only an indication, it doesn't enforce the header value.

I suggest you test the calls anyway using the curl (SoapUI, Postman or any other feasible tool) so you can see what the service REALLY returns. The "Response Code 0" message usually means some error response (400, 500, .. anything) it's just not necessarily shown in the DEV console.

Have fun