text:
Q: jQuery Code runs no matter what I have this jQuery code which is only suppose to show an alert for a new message when a record is found within the Database.
index.html (jQuery code)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

<script>

$(document).ready(function(){
    var count = 0;
    setInterval(function() {
        $.post("messagecheck.php", { countOld: count },
        function(data){
            if(data == 0) {
                alert("No New Messages");
                return;
         } else {
                count = data; // This will change the count for each run, you could store this in div with .data() ...
                alert("New Message!");
                return;
         }
            });
        }, 1000);
    });
</script>

messagecheck.php
<?php

    if($uid == 0) {
        die(); // not logged in
    } else {
        $sql = 'SELECT messagecount FROM Users WHERE uid = $uid AND messagecount >= 1';
        $result = mysql_query($sql);
        if(!$result) {
            // Kill SQL and return error
        } else {
            // We will be sending an Old Count via POST
            $numRows = mysql_num_rows($result);
            echo $numRows;
            if( $numRows == $_POST['countOld']) {
                // No change
                echo 'No change: 0';
            } else
                echo $numRows;
        }
    }

?>

Even if the $uid is 0 (user is not logged in) the alert for New Message! shows.
What can I do to fix this?
Thanks.

A: Here's your conditional:
if(data == 0) {

And here's what your AJAX call returns:
echo 'No change: 0';

The conditional evaluates to false because 'No change: 0' doesn't equal 0.

A: You have a lot of logic problems.

*

*If the user ID is 0 (not logged in) then you kill the PHP script; nothing is returned. This is not the same as false, it will evaluate as '' and '' !== 0.

*If the SQL statement fails, same problem.
You need to re-factor your PHP script to either return a consistent result no matter what. Something like this:
<?php
$new_messages = false;

if ($uid > 0) {
    $sql = 'SELECT messagecount FROM Users WHERE uid = ? AND messagecount >= 1';

    $stmt = $db->prepare($sql);
    $stmt->execute(array($uid));
    $row = $stmt->fetchObject();

    if (is_object($row) && intval($row->messagecount) !== intval($_POST['countOld'])) {
        $new_messages = true;
    }
}

header('Content-Type: application/json');

print json_encode(array(
    'new_messages' => $new_messages
));

This will return a boolean (true or false) value no matter what, which you can then test against in your JavaScript:
$.post('messagecheck.php', { countOld: count }, function(result) {
    if (result && result.new_messages) {
        if (result.new_messages === true) {
            alert('You have a new message.');
        }
    }
});

Also, don't use mysql_ functions, they're deprecated as per the warning on the PHP.net manual page: http://php.net/manual/en/function.mysql-query.php. Use PDO or MySQLi instead.

A: If the $uid is 0 then there will be no data sent from the server. data will be emtpy, so the data == 0 will evaluate to false. Try this:
if (!data) {
    alert("No New Messages");
    return;
} else {
    count = data;
    alert("New Message!");
    return;
}

A: There are basically six things that might be the issue - that I can think of:

*

*In PHP you're echoing out 'No change: 0'.

*You're using die(); as a return-value

*You're echoing out same number twice.

*$numRows and/or $_POST['countOld'] aren't returning expected
values

*In jQuery you're using ==. This operator evaluates a value

*You're executing ajax-code once a second and jQuery is doing async -
calls

Change part of PHP:
   } else {
        // We will be sending an Old Count via POST
        $numRows = mysql_num_rows($result);
        echo $numRows;
        if( $numRows == $_POST['countOld']) {
            // No change
            echo 'No change: 0';
        } else
            echo $numRows;
    }

to:
   } else {
        // We will be sending an Old Count via POST
        $numRows = mysql_num_rows($result);
        //Before you hade echo $numRows. This would make numRows echo out twice
        //because it's echoed it down below also
        if( $numRows == $_POST['countOld']) {
            // No change
            echo 0; //Echo out 0.
        } else
            echo $numRows;
    }

Why? Because echo 'No change: 0'; evaulates to false and no the value 0.
in jQuery (javascript) - use typeof to check the actual value, like this:
<script>
    $(document).ready(function(){
        var count = 0;
        setInterval(function() {
            $.post("messagecheck.php", { countOld: count },
            function(data){
                if(typeof data == 0) {
                    alert("No New Messages");
                    return;
             } else {
                    count = data; // This will change the count for each run, you could store this in div with .data() ...
                    alert("New Message!");
                    return;
             }
                });
            }, 1000);
        });
    </script>

Log/Inspect values of $numRows and $_POST['countOld'] and see if you'e getting what you're expecting.
You're executing ajax-code once a second and jQuery is doing async calls. If doing eveything above and all seems fine, I would change interval to a larger number just to be sure so the calls itself aren't screwing things up. I'm not sure you have to check as often as a second?
Instead of using die() when userid = 0, just echo out 0 with echo '0';. (then the script would not fail)
And of course - don't use mysql_ - functions* if you absolutely don't have to, because they're deprecated. And in you're case, it's open to sql-injections etc, but that is another issue.


text:
Q: Send data to the backend API Angular 6 i'm trying to send few form details to the backend API using angular6, but it doesn't work as i expected, and how do i add Observable to this, im expecting to use observable instead of promises.
login.component.html
loginUser(e){

    var username = e.target.elements[0].value;
    var password = e.target.elements[1].value;
    console.log(username,password);

      this.user.setUserLoggedIn()
      var body = "username=" + username + "password=" + password;
      this.http.post("http://localhost:8080/user/all", body).subscribe((data) => {});
       this.router.navigate(['fullpage'])

    return false;
  }

login.component.html
<form id="loginForm" novalidate="novalidate" (submit)="loginUser($event)">

                                        Username
                                        <input type="text" class="form-control" id="username" name="username" value="" required="" title="Please enter you username" placeholder="example@gmail.com">

                                        Password
                                        <input type="password" class="form-control" id="password" name="password" value="" required="" title="Please enter your password" placeholder="******">

Wrong username or password

                                    <button type="submit" class="btn btn-success btn-block">Login</button>

                                </form>

Error:

ERROR Error: Uncaught (in promise): Error:
  StaticInjectorError(AppModule)[LogincomponentComponent -> Http]:
  StaticInjectorError(Platform: core)[LogincomponentComponent -> Http]:
      NullInjectorError: No provider for Http! Error: StaticInjectorError(AppModule)[LogincomponentComponent -> Http]:
  StaticInjectorError(Platform: core)[LogincomponentComponent -> Http]:
      NullInjectorError: No provider for Http!

A: You should import HttpModule or HttpClientModule in app.module file
and add it to imports array
If your http object is of type Http import HttpModule
If your http object is of type HttpClient import HttpClientModule
and body object is not of type string it is object type
it should be
body = { username, password }

A: You need to Add http module into your app.module like this -
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [],
  imports: [HttpModule]
...

PS:

*

*If you are using HttpClientModule make changes accordingly

*HttpModule is deprecated in v>5

A: In order to use Http in your app you will need to add the HttpModule to your app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule
  ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find $A^n$ for n=0,1, and 3: Languages and Finite State Machines The question is:
Let $A$={11,00}.
Find $A^n$ for n=0,1, and 3.
Would i be right in thinking that
$A^0$ = {λ}
$A^1$ = {11,00}
$A^3$ = {111111,111100,110011,110000,000011,000000,001100,001111}.
if not, please could you help point me in the right drection?


text:
Q: Self-join not working as expected with the DataFrame API I am trying to get the latest records from a table using self join. It works using spark-sql but not working using spark DataFrame API.
Can anyone help? Is it a bug?
I am using Spark 2.2.0 in local mode
Creating input DataFrame:
scala> val df3 = spark.sparkContext.parallelize(Array((1,"a",1),(1,"aa",2),(2,"b",2),(2,"bb",5))).toDF("id","value","time")
df3: org.apache.spark.sql.DataFrame = [id: int, value: string ... 1 more field]

scala> val df33 = df3
df33: org.apache.spark.sql.DataFrame = [id: int, value: string ... 1 more field]

scala> df3.show
+---+-----+----+
| id|value|time|
+---+-----+----+
|  1|    a|   1|
|  1|   aa|   2|
|  2|    b|   2|
|  2|   bb|   5|
+---+-----+----+

scala> df33.show
+---+-----+----+
| id|value|time|
+---+-----+----+
|  1|    a|   1|
|  1|   aa|   2|
|  2|    b|   2|
|  2|   bb|   5|
+---+-----+----+

Now performing the join using SQL: works
scala> spark.sql("select df33.* from df3 join df33 on df3.id = df33.id and df3.time < df33.time").show
+---+-----+----+
| id|value|time|
+---+-----+----+
|  1|   aa|   2|
|  2|   bb|   5|
+---+-----+----+

Now performing the join using dataframe API: doesn't work
scala> df3.join(df33, (df3.col("id") === df33.col("id")) && (df3.col("time") < df33.col("time")) ).select(df33.col("id"),df33.col("value"),df33.col("time")).show
+---+-----+----+
| id|value|time|
+---+-----+----+
+---+-----+----+

The thing to notice is the explain plans: blank for the DataFrame API!!
scala> df3.join(df33, (df3.col("id") === df33.col("id")) && (df3.col("time") < df33.col("time")) ).select(df33.col("id"),df33.col("value"),df33.col("time")).explain
== Physical Plan ==
LocalTableScan <empty>, [id#150, value#151, time#152]

scala> spark.sql("select df33.* from df3 join df33 on df3.id = df33.id and df3.time < df33.time").explain
== Physical Plan ==
*Project [id#1241, value#1242, time#1243]
+- *SortMergeJoin [id#150], [id#1241], Inner, (time#152 < time#1243)
   :- *Sort [id#150 ASC NULLS FIRST], false, 0
   :  +- Exchange hashpartitioning(id#150, 200)
   :     +- *Project [_1#146 AS id#150, _3#148 AS time#152]
   :        +- *SerializeFromObject [assertnotnull(input[0, scala.Tuple3, true])._1 AS _1#146, staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString,
assertnotnull(input[0, scala.Tuple3, true])._2, true) AS _2#147, assertnotnull(input[0, scala.Tuple3, true])._3 AS _3#148]
   :           +- Scan ExternalRDDScan[obj#145]
   +- *Sort [id#1241 ASC NULLS FIRST], false, 0
      +- Exchange hashpartitioning(id#1241, 200)
         +- *Project [_1#146 AS id#1241, _2#147 AS value#1242, _3#148 AS time#1243]
            +- *SerializeFromObject [assertnotnull(input[0, scala.Tuple3, true])._1 AS _1#146, staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString,
assertnotnull(input[0, scala.Tuple3, true])._2, true) AS _2#147, assertnotnull(input[0, scala.Tuple3, true])._3 AS _3#148]
               +- Scan ExternalRDDScan[obj#145]

A: No that's not a bug, but when you reassign the DataFrame to a new one like what you have done, it actually copies the lineage but it doesn't duplicate the data. Thus you'll be comparing on the same column.
Use spark.sql is slightly different because it's actually working on aliases of your DataFrames
So the correct way to perform a self-join using the API is actually aliasing your DataFrame as followed :
val df1 = Seq((1,"a",1),(1,"aa",2),(2,"b",2),(2,"bb",5)).toDF("id","value","time")

df1.as("df1").join(df1.as("df2"), $"df1.id" === $"df2.id" && $"df1.time" < $"df2.time").select($"df2.*").show
// +---+-----+----+
// | id|value|time|
// +---+-----+----+
// |  1|   aa|   2|
// |  2|   bb|   5|
// +---+-----+----+

For more information about self-joins, I recommend reading  High Performance Spark by Rachel Warren, Holden Karau - Chapter 4.


text:
Q: Querying MySQL, duration increases 10x fold after adding one more Join I have a somewhat complicated query consisting of many joins on an issue tracker/project management database in MySQL.
My issue is that my query was doing OK while I was in the process of building it up, but after the addition of one final join, the query performance (duration) is no longer tolerable.
The query below ran fine with a duration of ~15 seconds, which is acceptable...
SELECT distinct p.name, (i_A.hours + i_B.hours + i_C.hours),
    (COALESCE(cv_db2_A.value,0) + COALESCE(cv_db2_B.value,0) + COALESCE(cv_db2_C.value,0)),
    (COALESCE(cv_db3_A.value,0) + COALESCE(cv_db3_B.value,0) + COALESCE(cv_db3_C.value,0)),
    i_A.hours, if (cv_db2_A.value='',NULL,cv_db2_A.value), if (cv_db3_A.value='',NULL,cv_db3_A.value),
    i_B.hours, if (cv_db2_B.value='',NULL,cv_db2_B.value), if (cv_db3_B.value='',NULL,cv_db3_B.value),
    i_C.hours, if (cv_db2_C.value='',NULL,cv_db2_C.value), if (cv_db3_C.value='',NULL,cv_db3_C.value),
    i_date.due_date
    FROM projects p, issues i_team_1, issue_statuses ist,
        issues i_A, issues i_B, issues i_C,
        custom_values cv_db2_A, custom_values cv_db3_A,
        custom_values cv_db2_B, custom_values cv_db3_B,
        custom_values cv_db2_C, custom_values cv_db3_C,
        issues i_date
    WHERE i_date.project_id = p.id and
        ist.id = i_team_1.status_id and
        i_team_1.project_id = p.id and
        i_team_1.tracker_id = 23 and i_team_1.subject like 'Group1' and
        i_A.project_id = p.id and i_B.project_id = p.id and i_C.project_id = p.id and
        i_A.subject = 'A Hours' and i_B.subject = 'B Hours' and i_C.subject = 'C Hours' and
        cv_db2_A.custom_field_id = 172 and cv_db2_A.customized_id = i_A.id and
        cv_db3_A.custom_field_id = 173 and cv_db3_A.customized_id = i_A.id and
        cv_db2_B.custom_field_id = 172 and cv_db2_B.customized_id = i_B.id and
        cv_db3_B.custom_field_id = 173 and cv_db3_B.customized_id = i_B.id and
        cv_db2_C.custom_field_id = 172 and cv_db2_C.customized_id = i_C.id and
        cv_db3_C.custom_field_id = 173 and cv_db3_C.customized_id = i_C.id and
        i_date.tracker_id = 4 and i_date.subject like 'Date' and
        i_date.due_date BETWEEN CAST('2014-01-01' AS DATE) AND CAST('2014-12-11' AS DATE) and
        p.name NOT LIKE '# Temp%';

I then proceeded to add one more join into the mix by:
adding in one more "issues i_team_2" and 3 related "WHERE" conditions.
SELECT p.name, (i_A.hours + i_B.hours + i_C.hours),
    (COALESCE(cv_db2_A.value,0) + COALESCE(cv_db2_B.value,0) + COALESCE(cv_db2_C.value,0)),
    (COALESCE(cv_db3_A.value,0) + COALESCE(cv_db3_B.value,0) + COALESCE(cv_db3_C.value,0)),
    i_A.hours, if (cv_db2_A.value='',NULL,cv_db2_A.value), if (cv_db3_A.value='',NULL,cv_db3_A.value),
    i_B.hours, if (cv_db2_B.value='',NULL,cv_db2_B.value), if (cv_db3_B.value='',NULL,cv_db3_B.value),
    i_C.hours, if (cv_db2_C.value='',NULL,cv_db2_C.value), if (cv_db3_C.value='',NULL,cv_db3_C.value),
    i_date.due_date
    FROM projects p, issues i_team_1, issues i_team_2, issue_statuses ist,
        issues i_A, issues i_B, issues i_C,
        custom_values cv_db2_A, custom_values cv_db3_A,
        custom_values cv_db2_B, custom_values cv_db3_B,
        custom_values cv_db2_C, custom_values cv_db3_C,
        issues i_date
    WHERE i_date.project_id = p.id and
        ist.id = i_team_1.status_id and
        i_team_1.project_id = p.id and i_team_2.project_id = p.id and
        i_team_1.tracker_id = 23 and i_team_1.subject like 'Group1' and
        i_team_2.tracker_id = 23 and i_team_2.subject like 'Group2' and
        i_A.project_id = p.id and i_B.project_id = p.id and i_C.project_id = p.id and
        i_A.subject = 'A Hours' and i_B.subject = 'B Hours' and i_C.subject = 'C Hours' and
        cv_db2_A.custom_field_id = 172 and cv_db2_A.customized_id = i_A.id and
        cv_db3_A.custom_field_id = 173 and cv_db3_A.customized_id = i_A.id and
        cv_db2_B.custom_field_id = 172 and cv_db2_B.customized_id = i_B.id and
        cv_db3_B.custom_field_id = 173 and cv_db3_B.customized_id = i_B.id and
        cv_db2_C.custom_field_id = 172 and cv_db2_C.customized_id = i_C.id and
        cv_db3_C.custom_field_id = 173 and cv_db3_C.customized_id = i_C.id and
        i_date.tracker_id = 4 and i_date.subject like 'Date' and
        i_date.due_date BETWEEN CAST('2014-01-01' AS DATE) AND CAST('2014-12-11' AS DATE) and
        p.name NOT LIKE '# Temp%';

This one additional join causes my query time to increase 10x from ~15 seconds to ~160 seconds.

*

*I have tried omitting the "WHERE" conditions for "i_team_2" and it made the query time go down to about ~110 seconds... which is still not acceptable.

The EXPLAIN function shows 14 "SIMPLE" select type actions. Each one is using an index/key and the number of rows checked for each action does not show a number higher than 150 for any of them.
    EXPLAIN: BEFORE
id  select_type table       type    possible_keys                                                           key                                     key_len ref                     rows    Extra
1   SIMPLE      cv_db3_A    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   163     Using temporary
1   SIMPLE      i_A         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_A.customized_id  1       Using where
1   SIMPLE      p           eq_ref  PRIMARY                                                                 PRIMARY                                 4       i_A.project_id          1       Using where
1   SIMPLE      i_team_1    ref     issues_project_id,index_issues_on_status_id,index_issues_on_tracker_id  issues_project_id                       4       i_A.project_id          9       Using where
1   SIMPLE      ist         eq_ref  PRIMARY                                                                 PRIMARY                                 4       i_team_1.status_id      1       Using index
1   SIMPLE      cv_db3_B    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   163
1   SIMPLE      i_B         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_B.customized_id  1       Using where
1   SIMPLE      cv_db3_C    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   163
1   SIMPLE      i_C         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_C.customized_id  1       Using where
1   SIMPLE      i_date      ref     issues_project_id,index_issues_on_tracker_id                            issues_project_id                       4       i_A.project_id          9       Using where
1   SIMPLE      cv_db2_A    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   164     Using where
1   SIMPLE      cv_db2_B    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   164     Using where
1   SIMPLE      cv_db2_C    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   164     Using where

    EXPLAIN: AFTER
id  select_type table       type    possible_keys                                                           key                                     key_len ref                     rows    Extra
1   SIMPLE      cv_db3_A    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   144     Using temporary
1   SIMPLE      i_A         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_A.customized_id  1       Using where
1   SIMPLE      p           eq_ref  PRIMARY                                                                 PRIMARY                                 4       i_A.project_id          1       Using where
1   SIMPLE      i_team_1    ref     issues_project_id,index_issues_on_status_id,index_issues_on_tracker_id  issues_project_id                       4       i_A.project_id          10      Using where
1   SIMPLE      ist         eq_ref  PRIMARY                                                                 PRIMARY                                 4       i_team_1.status_id      1       Using index
1   SIMPLE      cv_db3_B    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   144
1   SIMPLE      i_B         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_B.customized_id  1       Using where
1   SIMPLE      cv_db3_C    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   144
1   SIMPLE      i_C         eq_ref  PRIMARY,issues_project_id                                               PRIMARY                                 4       cv_db3_C.customized_id  1       Using where
1   SIMPLE      i_team_2    ref     issues_project_id,index_issues_on_tracker_id                            issues_project_id                       4       i_A.project_id          10      Using where
1   SIMPLE      i_date      ref     issues_project_id,index_issues_on_tracker_id                            issues_project_id                       4       i_A.project_id          10      Using where
1   SIMPLE      cv_db2_A    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   145     Using where; Distinct
1   SIMPLE      cv_db2_B    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   145     Using where; Distinct
1   SIMPLE      cv_db2_C    ref     index_custom_values_on_custom_field_id                                  index_custom_values_on_custom_field_id  4       const                   145     Using where; Distinct

Note: The "BEFORE" EXPLAIN has higher number of rows due to additions to the data and was taken after the "AFTER" EXPLAIN.

The Sense of the Query:
I am trying to grab information (i.e. kinds of hours worked ("db2" or "db3") divided per subject area/field (3 different fields: "A","B","C")) for particular project types (i.e. "Group1" or "Group2" project types) that has a certain kind of date fall within a given date range.

In this particular query, I am grabbing the 6 different information fields for project types that include both "Group1" and "Group2" only (intersect, not union).

Note: I accidentally forgot to include the actual data/columns I am retrieving in the SELECT statements above (I pasted my debugging version). However, testing with or without that portion has not given me any advantage in performance and, in conclusion, is not where the problem resides.

Question

*

*Am I doing anything wrong?

*How can I shorten this query's duration to a more manageable amount?

*Should I split the query up?

A: You have forgotten the join criteria and ist.id = i_team_2.status_id.
If you had used the modern JOIN syntax this would have stood out like a sore thumb.

A: Looking at the EXPLAIN and examining the indices did not help me (maybe I did not try hard (or correctly) enough).
My final solution was to not JOIN together so many instances of large tables (in this case, the "issues" tables). In effect, I split up the query into two queries and now my querying performance is much less than 1 second.


text:
Q: Heroku Rails application Asset Management I am using rails 4.2.0 + amazon clodfront + Heroku.
In my config/environments/production.rb i have this config set to true.
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true

I frequently asks myself whether this should be set to false or not?
As I am confused whether should i manually compile the assets and then push it to heroku,
or set it to true?
Please suggest me the best practice.

A: From the perspective of using a CDN like Amazon CloudFront not much. The advantage to setting this to false is that the files are hashed and cached to speed load times. When you migrate your assets to a CDN it handles caching instead of Rails.  When the value is set to true the assets do not have the hash which can be useful if you have users requesting assets that are older and may not match the current hash.


text:
Q: How to simulate a clicking at this on/off button in python selenium? I am trying to write a selenium code to simulate a switch on/off action.
This is the UI of that application and its actual source code under:

As we can see the label::before is mapped to "on" action, and label::after is for "off".
Following is my current python code that is not able to make such click.
def turnoff_byPlanCapacity(self):
    try:
        by_Plan_Capacity     =  "//div[contains(text(), 'Modem1 Settings')]/following-sibling:div[2]/div[2]/div[1]/div[2]/div/label"
        WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.XPATH, by_Plan_Capacity))).click()
    except Exception as e:
        self.logger.info(e)
        raise

Does anyone know a solution for it ? Thanks a lot

A: To simulate clicking on the On / Off button you can use either of the following Locator Strategies:

*

*Using css_selector:
driver.find_element(By.CSS_SELECTOR, "label[for*='byPlanCapacity']").click()

*Using xpath:
driver.find_element(By.XPATH, "//label[starts-with(@for, 'byPlanCapacity')]").click()

The desired element is a dynamic element, so ideally to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for*='byPlanCapacity']"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[starts-with(@for, 'byPlanCapacity')]"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Your effective code block will be:
def turnoff_byPlanCapacity(self):
    try:
        WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[starts-with(@for, 'byPlanCapacity')]"))).click()
    except Exception as e:
        self.logger.info(e)
    raise

A: Please use this xpath
//input[starts-with(@id,'byPlanCapacity') and @type='checkbox']//following-sibling::label

Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
If we have unique entry in HTMLDOM, then
def turnoff_byPlanCapacity(self):
    try:
        by_Plan_Capacity = "//input[starts-with(@id,'byPlanCa[acity') and @type='checkbox']//following-sibling::label"
        WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, by_Plan_Capacity))).click()
    except Exception as e:
        self.logger.info(e)
        raise

Note that I am using element_to_be_clickable instead of presence_of_element_located


text:
Q: To accelerate FunctionCompile I have a function value like this:
groups = N[{{40, 23, 213, 79, 18, 152, 105, 191, 119, 243}, {86, 3, 152, 89,
     52, 36, 132, 196, 159, 108, 200}, {253, 223, 167, 197, 147, 112,
     225, 98, 159, 163, 245, 240, 267}, {89, 164, 156, 124, 15, 253,
     41, 171, 209, 132}}];

PopulationVariance1[list_] := Mean[(list - Mean[list])^2]

value[groups_] := Module[{mean, SSA, SSE}, mean = Mean[Flatten[groups]];
  SSA = Total[Table[Length[group]*(Mean[group] - mean)^2, {group, groups}]];
  SSE = Total[Table[Length[group]*PopulationVariance1[group], {group, groups}]];
  (SSA/(Length[groups] - 1))/(SSE/(Length[Flatten[groups]] - Length[groups]))]

value[groups]

3.6118

This is my current compilation try:
dec = FunctionDeclaration[PopulationVariance,
   Typed[{"PackedArray"::["Real64", 1]} -> "Real64"]@
    Function[list, Mean[(list - Mean[list])^2]]];

cfvalue = FunctionCompile[dec,
  Function[Typed[groups, "ListVector"::["ListVector"::["Real64"]]],
   Module[{mean, SSA, SSE},
    mean = Mean[
      Cast[Catenate[groups], "PackedArray"::["Real64", 1]]];
    SSA = Total[Cast[
       Length[#]*(Mean[Cast[#, "PackedArray"::["Real64", 1]]] -
             mean)^2 & /@ groups, "PackedArray"::["Real64", 1]]];
    SSE = Total[Cast[
       Length[#]*PopulationVariance[
           Cast[#, "PackedArray"::["Real64", 1]]] & /@ groups,
       "PackedArray"::["Real64", 1]]];
    (SSA/(Length[groups] - 1))/(SSE/(Length[Catenate[groups]] -
         Length[groups]))]]]

cfvalue[groups]

3.6118

It works indeed. However, I found that the compiler function was even slower than the uncompiled one.
lis = DeleteCases[Table[ResourceFunction["RandomSplit"][RandomReal[255, 1000], 10],
    100000], {}, {2}];
Timing[value /@ lis;](*{15.2813, Null}*)
Timing[cfvalue /@ lis;](*{23., Null}*)

Could you please help me improve the speed of the cfvalue?

$Version

13.1.0 for Microsoft Windows (64-bit) (June 16, 2022)

A: I decide to use Rust to show how much improvement we can achieve while also benefiting from the Rust memory management system which prevents us to leak memory (to some extent).
Recently Wolfram started a project called wolfram-library-link-rs which is a Rust crate (aka library/module/etc) which allows users to code in Rust and export their functions without doing much for the interface with Mathematica.
To follow this workflow you need to install Rust and have an internet connection when you build the project (I think only the first time is required).
Create a Rust project, replace Cargo.toml content with the following:
[package]
name = "population_variance"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
wolfram-library-link = "0.2.5"

and replace src/lib.rs content with this:
use wolfram_library_link::{export, NumericArray};

type Precision = f64;
type ArrayType = Precision;

fn population_variance(array: &[ArrayType]) -> Precision {
    let mean = array.iter().sum::<ArrayType>() as f64 / array.len() as Precision;
    array.iter().map(|&x| (x as Precision - mean).powf(2.0)).sum::<Precision>() as Precision / array.len() as Precision
}

fn value(groups: Vec<&[ArrayType]>) -> Precision {
    let total: ArrayType = groups.iter().map(|group| group.iter().sum::<ArrayType>()).sum::<ArrayType>();
    let flatten_length: usize = groups.iter().map(|group| group.len()).sum();
    let mean = total as Precision / flatten_length as Precision;
    let groups_len = groups.len();

    let ssa = groups.iter().map(|group| group.len() as Precision * ((group.iter().sum::<ArrayType>() as Precision) / (group.len() as Precision) - mean).powf(2.0)).sum::<Precision>();
    let sse = groups.iter().map(|group| group.len() as Precision * population_variance(group)).sum::<Precision>();
    (ssa / (groups_len - 1) as Precision) / (sse / (flatten_length - groups_len) as Precision)
}

#[export]
fn mathematica_interface(data: &NumericArray<ArrayType>, lengths: &NumericArray<i64>) -> Precision {
    let data_slice = data.as_slice();
    let mut vectors: Vec<&[ArrayType]> = Vec::with_capacity(lengths.flattened_length());
    let mut current_index: usize = 0;
    for &length in lengths.as_slice() {
        let length = length as usize;

        vectors.push(&data_slice[current_index..(current_index + length)]);
        current_index += length;
    }

    value(vectors)
}

When you build the project (with build --release), you will get a population_variance.dll in the target/release directory.
In Mathematica use the following code to use the library (change the path to your address):
compiledValue =
 LibraryFunctionLoad["C:\\population_variance.dll",
  "mathematica_interface", {{LibraryDataType[NumericArray, "Real64"],
    "Constant"}, {LibraryDataType[NumericArray, "Integer64"],
    "Constant"}}, Real];

ClearAll[RustValue];

RustValue[data_] := Block[{lengths = Length /@ data},
  compiledValue[NumericArray[Flatten@data, "Real64"],
   NumericArray[lengths, "Integer64"]]
  ]

Now it will work as a normal function:
Block[{data = N@{{1, 2, 3}, {4, 5, 6, 7, 9}}},
 {value[data], cfvalue[data], RustValue[data]}
 ]

(* Out: {11.8125, 11.8125, 11.8125} *)

Testing larger dataset:
Block[{data = N@lis},
 {value /@ data // Total // AbsoluteTiming,
  cfvalue /@ data // Total // AbsoluteTiming,
  RustValue /@ data // Total // AbsoluteTiming}
 ]

(* Out: {{19.3707, 100129.}, {32.3437, 100129.}, {5.59327, 100129.}} *)

If you want to measure only the calculation on compiled code without including the time needed for converting the input:
Block[{a = NumericArray[Flatten@#, "Real64"] & /@ lis,
   b = NumericArray[Length /@ #, "Integer64"] & /@ lis},
  MapThread[compiledValue, {a, b}] // Total // AbsoluteTiming
  ] // AbsoluteTiming

(* Out: {5.96117, {0.416077, 100129.}} *)

The first timing (5.96) is for the whole operation, the second (0.41) is for the compiled code, and 100129. exist to show it returns the same result as shown before.
How did we handle ragged arrays
As you might have seen, our compiled function has two arguments, first the flattened data and second the length of each list. In Rust, we partitioned the data like TakeList.
Note that I still have so many things to learn and I'm sure the code above can be further improved.

A: Add a method from this post:
Needs["CCompilerDriver`"]
lib=CCompilerDriver`CreateLibrary["
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include \"WolframCompileLibrary.h\"

using namespace std;

struct ManagedArray{
    MTensor* data;
    mint refcount;
};

struct FixedArray{
    ManagedArray data;
    mint refcount;
};

struct RaggedList{
    FixedArray* data;
    mint refcount;
};

mreal value(vector<vector<mreal>> pix_values) {
    vector<mreal> flatten_pix_values;
    for (auto const& group : pix_values) {
        flatten_pix_values.insert(flatten_pix_values.end(), group.begin(), group.end());
    }

    mreal mean_value = std::accumulate(begin(flatten_pix_values), end(flatten_pix_values), 0.0) / flatten_pix_values.size();

    mreal SST = 0.0;
    for_each(begin(flatten_pix_values), end(flatten_pix_values), [&SST, mean_value](const mreal d) {SST += pow(d - mean_value, 2); });

    mreal SSA = 0;
    for (auto const& group : pix_values) {
        SSA += group.size() * pow(std::accumulate(begin(group), end(group), 0.0) / group.size() - mean_value, 2);
    }
    mreal SSE = SST - SSA;
    int a = pix_values.size() - 1, b = flatten_pix_values.size() - pix_values.size();

    return mreal((SSA / a) / (SSE / b));
}

EXTERN_C DLLEXPORT mreal ragged_value(RaggedList inlis) {
    vector<vector<mreal>> vecs;

    for (mint i = 0; i < inlis.data->data.refcount; i++) {
        MTensor tensor = inlis.data->data.data[i];
        auto ptensor = (mreal*)tensor->data;
        vector<mreal> vec(ptensor, ptensor + tensor->nelems);
        vecs.push_back(vec);
    }

    return value(vecs);
}","Ragged_Value",Language->"C++"];
dec=LibraryFunctionDeclaration[fun->"ragged_value",lib,{"ListVector"::["PackedArray"::["Real64",1]]}->"Real64"];
fcvalue=FunctionCompile[dec,Function[{Typed[lis,"ListVector"::["PackedArray"::["Real64",1]]]},fun[lis]]]

Performance
lis = DeleteCases[
   Table[ResourceFunction["RandomSplit"][RandomReal[255, 1000], 10],
    100000], {}, {2}];
RepeatedTiming[value /@ lis;]
RepeatedTiming[fcvalue /@ lis;]

{11.0433, Null}

{2.42399, Null}

A: The Code
Here's some equivalent code that performs a better:
cfValue =
 FunctionCompile[
  Function[Typed[groups, "ListVector"::["PackedArray"::["Real64", 1]]],
   Module[{
     PopulationVariance =
      Function[{Typed[g, "PackedArray"::["Real64", 1]]},
       Mean[(g - Mean[g])^2]
       ], mean, total, SSA, SSE, len},

    total =
     Fold[Plus[#1, #2] &,
      Map[Typed[Total, {"PackedArray"::["Real64", 1]} -> "Real64"],
       groups]];
    len =
     Fold[Plus[#1, #2] &,
      Map[Typed[
        Length, {"PackedArray"::["Real64", 1]} -> "Integer64"],
       groups]];

    mean = total/ len;

    SSA =
     Fold[Plus[#1, #2] &, Length[#]*(Mean[#] - mean)^2 & /@ groups];
    SSE =
     Fold[Plus[#1, #2] &,
      Map[Length[#]*PopulationVariance[#] &, groups]];
    (SSA/(Length[groups] - 1))/(SSE/(len - Length[groups]))
    ]
   ]
  ]

Timing
On my machine with Mathematica 13.1:
In[111]:= AbsoluteTiming[cfValue[#] & /@ lis;]

Out[111]= {3.04551, Null}

In[112]:= AbsoluteTiming[value[#] & /@ lis;]

Out[112]= {10.4156, Null}

Why
The casting in code from the question was cloning the data each time which is very expensive.
This function avoids casting by instead using a Fold with Plus to total the ListVectors.


text:
Q: Нет каталога aptitude Я установил aptitude, изменил некоторые параметры в нем, у меня есть задание:
Достаточно скопировать файл config
в директорию /root/.aptitude/:
cp -f ./aptitude/config /root/.aptitude/config
Но у меня нет каталога /aptitude, никак не могу найти файл /aptitude/config
Как быть?


text:
Q: R flatten out list hierarchy to matrix or data.frame I would like to flatten out a list hierarchy (similar to JSON) to a matrix or data frame. Let's say that I create the following list:
a <- list(
  b1 = list(
     c1 = list(
       d1 = data.frame()
     ),
     c2 = data.frame()
  ),
  b2 = data.frame()
)

Where each letter is another level or step down the hierarchy. Then I want a function, e.g. listToMatrix(mylist = a, steps = 2), that generates the following:
    [,1] [,2]
[1,] "b1" "c1"
[2,] "b1" "c2"
[3,] "b2" "b2"

Observe that the function's argument steps = 2 imply that it should only go 2 steps down the hierarchy. Also, if there aren't enough levels available in one direction, see b2, then it should keep the previous list name in the matrix.
Any suggestions? :)

A: Here is a solution. So it reads easily here, I have broken the code into two parts. Later, you can easily merge the two parts into a single function.
First, a function that gets a matrix of all the names, using recursion:
anames <- function(x) {

   require(plyr)
   if (is.data.frame(x)) return(NA)

   y <- do.call(rbind.fill.matrix,
                mapply(cbind, names(x), lapply(x, anames),
                       SIMPLIFY = FALSE))
   colnames(y) <- NULL

   return(y)
}

anames(a)
#      [,1] [,2] [,3] [,4]
# [1,] "b1" "c1" "d1" NA
# [2,] "b1" "c2" NA   NA
# [3,] "b2" NA   NA   NA

Then, a function that applies the given steps input, and fills the NAs like you requested:
listToMatrix <- function(myList, steps = Inf) {

   a <- anames(myList)
   steps <- min(steps, ncol(a) - 1)
   cols.idx <- seq_len(steps)
   a <- a[, cols.idx]
   for (j in tail(cols.idx, -1))
      a[, j] <- ifelse(is.na(a[, j]), a[, j - 1], a[, j])

   return(a)
}

listToMatrix(a, 2)
#      [,1] [,2]
# [1,] "b1" "c1"
# [2,] "b1" "c2"
# [3,] "b2" "b2"


text:
Q: Stop a timer on an if statement within a view I'am quite new to Swift and I despair of a problem.
I created a class with two functions to start and stop a timer.
There's a struct that starts the timer (start function) with onAppear.
Within the struct there's a button to stop the time.
import SwiftUI

class StopWatch: ObservableObject {
    @Published var secondsElapsed = 0.0
    var timer = Timer()

    func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
            self.secondsElapsed += 0.1 }
    }
    func stopTimer() {
        timer.invalidate()
    }
}

struct Test: View {
    @ObservedObject var stopWatch = StopWatch()
    var body: some View {
        VStack{
            Button("Stop") {
                stopWatch.stopTimer()
            }
            Text(String(format: "%.1f", self.stopWatch.secondsElapsed))
        }.onAppear(perform: {stopWatch.startTimer()})
    }
}

The timer starts if the view starts. So far so good :-).
But I want to get rid of the stop button and replace it with an if statement like:
if stopWatch.secondsElapsed > 5.0 {
stopWatch.stopTimer() }
I want to stop the timer without a user action by this if statement and the current timer value should show up.
I tried for hours, but I didn't get it. For that case I get the error message "Type '()' cannot conform to 'View'", but I tried a lot of other things and got a lot of other errors.
Can anyone help me?

A: If you want the timer to stop on 5 seconds you should probably do this in the closure from the timer. You can do this:
func startTimer() {
    timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
        self.secondsElapsed += 0.1
        if self.secondselapsed == 5.0 {
            timer.invalidate()
        }
    }
}

You get this error ("Type '()' cannot conform to 'View'") because you try to execute code within the body of a SwiftUI view without returning a view. If you really want to do this in the body for some reason you could do it like this: (I would not recommend doing this)
if stopWatch.secondsElapsed > 5.0 {
    Text("Five seconds elapsed")
        .onAppear {
            stopWatch.stop()
        }
}


text:
Q: sbteclipse 1.0 not creating eclipse project with scala version 2.11.8 mentioned in build.sbt Please find the version used :
SBT version 1.0
Scala IDE 4.7
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.2.3")
I am trying to create a eclipse project but the project is getting created with scala version  2.12.3 where as my build.sbt mentions scala version 2.11.8.
As per my understanding project should get created by version mentioned in the build.sbt and the default version in scala ide.
build.sbt mentions the below version
scalaVersion := "2.11.8"


text:
Q: Intuition behind a conditional expectation in a Poisson process Earthquakes occur according to a Poisson process with $\lambda = 5$ per year, let $T_1$ be the time of the first occurrence of the process and we wish to figure out what is the average time that will pass until we reach a period of 3 months without any earthquakes.
So, if we define $X$ as the random variable which describes the time until we get a period of 3 months without earthquakes we have that:
\begin{align*}
E[X] &= E\left[X|T_1 > \frac{1}{4}\right]\cdot P \left\{ T_1 > \frac{1}{4}\right\} + E\left[X|T_1 \leq \frac{1}{4}\right]\cdot P \left\{ T_1 \leq \frac{1}{4}\right\}\\
&=0 + E\left[X|T_1 \leq \frac{1}{4}\right]\cdot P \left\{ T_1 \leq \frac{1}{4}\right\}
\end{align*}
According to my notes, $E\left[X|T_1 \leq \frac{1}{4}\right] = E\left[T_1|T_1 < \frac{1}{4}\right] + E[X]$.
Can someone please explain why the previous equality holds and what is the intuition behind it?


text:
Q: RequireJS - initialize one dependend module first, before loading the others I am doing my first project with requireJS and instantly ran into a problem :)
I have created a module "main" which is the basic node where my app should initialize from.
The APP uses a REST API to communicate with the server, so I created an API module, too.
The problem is: I have to initialize the API module first, before any other modules that are dependend of it will be loaded and initialized.
I have found it impossible to do that, because if my main module requires both the API module, plus some module dependend on the API module, the whole thing will failed, because they both get loaded and initialized before my main module gets initialized (and does the basic configuration of the API module).
Does someone know a trick how to load one module first, initialize it by passing some parameters and THEN go on and continue with requiring the other modules?

A: never tried it with Node.js but this works for me in both Dojo AMD and RequireJS assuming you need to run a module but before running the module B module A has to run i simply do this
require(["path/ModuleA","require"],function(modA,req){

    req(["path/ModuleB"],function(modB){
        //do anything with ModuleB
    });

});

i hope this solves your answer, if that's the issue you are referring to, take care


text:
Q: Match floating number in powershell I have a struggle with matching HTML strings with PowerShell. The last two td elements have one integer(1) and floating number(11,793). The number 73480 never changes. This numbers(1 and 11,793) can switch their type(integer<=>floating). When i use [+-]?([0-9]*[.])?[0-9]+ in this case the code is not working. Any idea how to fix it?
$web = @"

    73480
    Сазлийка
    Гълъбово
    1
    11,793

"@
[regex]::Match($web,@"

    73480
    (\w+)
    (\w+)
    ([+-]?([0-9]*[.])?[0-9]+)
    ([+-]?([0-9]*[.])?[0-9]+)

"@).Groups[1,2,3,4].Value

After I execute the command there is no output(blank result).

A: Your text has a decimal comma but your regex tries to match a [.].
I'd also replace all the multiple spaces in the regex with \s*
The groups you select don't count the optional sub(group) catching the first fraction.
$web = @"

    73480
    SampleOne
    SampleTwo
    1
    11,793

"@

$RE = @"
\s*

\s*73480\s*
\s*(\w+)\s*
\s*(\w+)\s*
\s*([+-]?([0-9]*[,\.])?[0-9]+)\s*
\s*([+-]?([0-9]*[,\.])?[0-9]+)\s*
\s*

"@
[regex]::Match($web,$RE).Groups[1,2,3,5].Value

returns here:
SampleOne
SampleTwo
1
11,793

A: Regex parsing is never recommended for HTML.
If your HTML is valid XML (yours is not) you can also parse it as such (for simplicity - if you don't want to include any HTML-parsing libraries):
# (tested in pwsh v5.1)
([xml]'

    73480
    Сазлийка
    Гълъбово
    1
    11,793

').tr.td | % { $_.'#text'.Trim() }

Output:

73480
  Сазлийка
  Гълъбово
  1
  11,793

(Mind that you have to use quotes for the attribute values to make it valid XML.)


text:
Q: Mypy: how to specify list (or sequence) of mixed types? Here some code:
import typing

class A:
    def f(self):
        print("A")

class B:
    def f(self):
        print("B")

C = typing.Union[A,B]
Sequence_C = typing.Sequence[C]

a = A()
b = B()

d : Sequence_C = [a]+[b]

mypy provides this error:
error: List item 0 has incompatible type "B"; expected "A"

My (possibly incorrect) undestanding:
C = typing.Union[A,B]
Sequence_C = typing.Sequence[C]

means that instances of Sequence_C are either sequences of instances of A or sequences of instances of B.
I would like to create a type Sequence_C which are sequences of instances of both A and B.
My motivation is that I need a list of instances implementing a "f" method.
Note that being more explicit did not help:
import typing

class S:
    def f(self):
        raise NotImplementedError()

class A(S):
    def f(self):
        print("A")

class B(S):
    def f(self):
        print("B")

Sequence_S = typing.Sequence[S]

a = A()
b = B()

d : Sequence_S = [a]+[b]

(same error)

A: You need to tell the type checker that [a] and [b] are to be interpreted as Sequence_S, and not typing.Sequence[A] (or [B]) explicitly, e.g. like this:
import typing

class S:
    def f(self) -> None:
        raise NotImplementedError()

class A(S):
    def f(self) -> None:
        print("A")

class B(S):
    def f(self) -> None:
        print("B")

Sequence_S = typing.Sequence[S]

a: Sequence_S = [A()]
b: Sequence_S = [B()]

# Sequences don't support "+", see https://docs.python.org/3/glossary.html#term-sequence
d : Sequence_S = [*a, *b]


text:
Q: Chrome Adaware candy-box.biz My Chrome, version 36 in win7, keeps randomly spawn tabs with address  http://www.candy-box.biz/adv/index.php?url=......
I can't remove this adware/malware, I try:

*

*look for souspicious extentions

*look for souspicious tasks in the chrome task manager

*use the Junkware Removal Tools

*EDIT use the adware cleaner

*launch spybot

*clean the cache.

but none of this solution resolved the problem.
Can someone help me?

A: I finnally found the source of the problem:
It was The CandyBox3 program. I could find it in the Installed Program list. Unistall it is not enough
(actually the unistall program does not remove anything). I had to stop the procress cab.exe and aus.exe using Process Explorer and removing manually the directoryC:\Program Files (x86)\CandyBox3.0 .


text:
Q: Check directory file size to notify by email if it grows to a certain point I have an access 97 server on windows that crashes if it's file size grows to be 1GB. I need to either find a software or write something(in java) that checks the directory and notifies us by email if the file size grows to 900MB so we can fix it. Does anyone have any ideas on sofrware or ways to go about this? I'm pretty rusty at programming so any points or tips would help greatly.
Edit1: The growth rate is relatively slow(last time we had a problem was about 3 months ago), so I believe we want it to check every 15 min, if that changes anything.

A: *

*You can periodically check the size of the file using size() from the Files class in Java.
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

*If you have more files to check you can cycle and add up their total size. Within your while you want to put a sleep() or something similar to avoid using up all your CPU.

*To send an email, the package http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html provides an implementation of smtp client.


text:
Q: Bayes Chain Rule I have been reading a paper on Bayesian Networks and Analytical Hierarchy Process.  I want to try and apply it to some of my own data.
The author states that he uses Bayes Chain Rule to calculate the probability of a single event.  Can you just rearrange Bayes rule to calculate P(A)?  He hasn't shown any working out and just jumps to an answer that I can't seem to see where it comes from.
I eventually want to be able to complete a conditional probability table from weightings from the AHP.
Thank you
EDIT - This is part of my BN and I am trying to find the missing values enter image description here


text:
Q: How to get the last read activity time stamp of mnesia Is there any mechanism to get informed about the last activity performed on a mnesia datababse, inparticular, the timestamp?
my case is not restricted in write activities but I need to know the last read activity.
Thank you very much.

A: Mnesia is not general purpose database, it's more like a library. So, no, there is no such functionality. But you can implement it by yourself. Just create proxy module for mnesia and update timestamp each time any function from your module get called. Also, notice, since Erlang is concurrent and parallel there might be cases where different functions called simultaneously. So, before updating timestamp make sure it's value bigger than one that's already stored.


text:
Q: parameters for share button not passing when facebook automatically redirects to m.facebook I have a web based platform that displays a share button on mobile devices. I pass the correct FB-required params so the share opens up with a predefined URL, text and thumbnail image.
When viewing the site on a mobile device [specifically iOS based iphones and ipads], FaceBook automatically detects the fact that it's a mobile device and switches to m.facebook. But in doing so, all the params I sent are lost / ignored.
Does anyone know if this is a FaceBook bug, or is there a new set of params specific to the m.facebook site? If I change the f= line to m.facebook.com it doesn't seem to make a difference.
I send the following share command [again, it works fine on any regular web browser]
function doShare() {
    var d = document;
    var f = 'http://www.facebook.com/share';
    var l = d.location, e=encodeURIComponent;
    var p = '.php?src=bm&v=4&i=1262250767&s=100&p[url]=http%3A%2F%2Fqa2%2Eclear%2Dmenu%2Ecom%2FrestHome%2Ephp%3Fr%3D12&p[images][0]=http%3A%2F%2Fqa2%2Eclear%2Dmenu%2Ecom%2Fimages%2FrestLogos%2Flogo%2D12%2Ejpg&p[title]=Clear-Menu:+Novotel+Hotel+--+Netherlands+--+Den+Haag&p[summary]=This+is+marketing+text+that+will+be+included+on+a+FB+share+feed.';
    1;

    try {
        if (!/^(.*\.)?facebook\.[^.]*$/.test(l.host))
            throw(0);
        share_internal_bookmarklet(p)
    }
    catch(z) {
        a=function() {
            if (!window.open(f+'r'+p,'sharer','toolbar=0,status=0,resizable=1,width=626,height=436')) {
                l.href=f+'r'+p;
            }
        };
        if (/Firefox/.test(navigator.userAgent)) {
            setTimeout(a,0);
        }
        else {
            a();
        }
    }
    void(0);
}


text:
Q: If all the particles of a gas had the same speed, the same direction, did not collide, would the gas have a temperature? Excuse my poor English, I have a lot to learn.
If all the particles of a gas had the same speed, the same direction, did not collide and were not subject to any external force, would the gas have a temperature, despite the fact that the particles would have an average kinetic energy ?
And what if all the particles had the same speed, were not subject to an external force but had random directions? Does the gas have a temperature?
If a gas A (10000 particles) had 1000 times more particles than a gas B (10 particles) and the particles of each gas had the same average kinetic energy, would the two gases have the same temperature ?

A:
If all the particles of a gas had the same speed, the same direction,
did not collide and were not subject to any external force, would the
gas have a temperature,

What you are describing is the kinetic energy of a container of particles as a whole with respect to an external frame of reference, i.e., the macroscopic kinetic energy of the container of gas.
However, in addition to the collective motion and kinetic energy of the gas, there is also always the kinetic energy associated with the random motion of the gas particles with respect to the center of mass of the container of gas. The temperature of the gas is based on the average kinetic energy of the those molecules, not the collective kinetic energy of the container of molecules as a whole.

And what if all the particles had the same speed, were not subject to
an external force but had random directions? Does the gas have a
temperature?

But the random speed of the particles of a gas cannot have the same speed. they follow the Boltzmann distribution. Only the collective motion of the particles can have the same speed, and that collective motion does not influence the temperature of the gas.

If a gas A (10000 particles) had 1000 times more particles than a gas
B (10 particles) and the particles of each gas had the same average
kinetic energy, would the two gases have the same temperature ?

Yes.
But they would not have the same total internal energy. For an ideal gas, where the internal energy consists only of kinetic energy,  gas A would have 1000 times more internal energy than gas B.
Hope this helps.

A:
If all the particles of a gas had the same speed, the same direction, did not collide and were not subject to any external force, would the gas have a temperature, despite the fact that the particles would have an average kinetic energy ?

The kinetic definition of temperature is given in the rest frame of the bulk of matter consisting the gas.

It would not be a gas, and it would not have a temperature.The rest frame of your hypothesis has all the gas molecules at rest by definition.

And what if all the particles had the same speed, were not subject to an external force but had random directions? Does the gas have a temperature?

Yes, in the center of mass rest frame of the system there would be a temperature.

If a gas A (10000 particles) had 1000 times more particles than a gas B (10 particles) and the particles of each gas had the same average kinetic energy, would the two gases have the same temperature ?

If in the rest frame of the group,yes, by definition.

A: The short answer is that energy is not frame-invariant. Thermodynamics and, as a consequence Statistical Mechanics at equilibrium, assume that all the energies are measured in a reference frame where the center of mass of the system is at rest.
Therefore, independently of its speed, an ice cube keeps always the same temperature.


text:
Q: HDD recovery on Windows I recently tried to help someone out whose computer crashed (the reason why is not important for now) by recovering the HDD (i.e. remove it from the computer and plug into a docking station to backup the contents), but I'm running into trouble with Windows permissions and ownership.
People always think that because I'm an avid computer programmer and studying mathematics, I should somehow magically know the answers to all everyday computer problems, and it is really hard to convince them that those things are not really related (well they are, but programming and system management are completely different things).
Anyhow, when I plugged the HDD in my docking station and connected it to an other computer (both run Windows Vista, but that is not my choice) the partitions showed up as usual, but when I tried to look through the contents, all partitions were inaccessible  (permission denied). I have done this kind of thing before without a problem and the only difference then was that the HDD came from a Windows 7 machine. I figured out that the partitions and their contents still had the old security attributes for the different user accounts set and that somehow Windows was still respecting them. So I tried to add the proper permissions for my local Administrator account with: properties -> security -> edit -> add. I thought that this would recursively set the permissions on all underlying folders and objects, but it did not did the trick, but I could now see the contents of the partitions root at least (sub-directories and objects were still inaccessible).
While I was trying to decide what I would do next, I noticed that there were no object- and folder owners. I do not know exactly what the difference is between owning an object or having the security permissions for an object, but I tried adding ownership to my local user account too, like this: properties -> security -> advanced -> owner -> edit -> apply. And now the problem: halfway while granting ownership to my local user there came a dialog that said that I did not have permissions to change ownership. While investigating what went wrong this time, I noticed two things:

*

*I could read/write/execute every folder and object that was granted ownership (thus all folders and objects processed until the dialog appeared).

*Where there was 1 GB of free space on the partition, there was now only a few KB. It seemed that the granting of ownership took more than a gigabyte, which seemed way to much for some metadata to me.

I tried exactly the same approach, but then with different partitions and the same happened, except for one partitions where there was 20 GB of free space (no additional space was consumed on that partition).
Any thought about what is going on?

A: Generally speaking, you cannot move permission based filesystems from one independent operating system to another because the account IDs will not match between the systems. If the hard disk is considered as "external" or "removable" media, permission enforcement is relaxed. If the hard disk is attached and shows up as a "fixed hard disk" Windows will fully enforce permissions and, with the accounts not present on the new system, leave most of the files inaccessible.
If you would like to verify how the disk is attached, you can run this PowerShell command:
Get-WmiObject -Class Win32_DiskDrive | Format-Table Name,Model, MediaType
Regardless of the type, if you do not plan to ever put this disk back into the system it came from, you can perform a brute force takeover of the permissions if you have administrative permissions. (If you do want to use this disk in the other system, you will need to coax it into showing up as a removable or external drive.) From an elevated (administrator) command prompt, execute the following commands:
Brute Force Permission Reset
First, take ownership of everything on the drive (this will just set the owner, not create large ACLs that take disk space) The owner of an object in NT has an inherent, non-revocable right to change permissions of the object. This will ensure that you have permission to perform the next commands.
TAKEOWN /F X:\ /R /D Y
Next, reset (remove) all the ACLs on all the filesystem objects. This will get rid of unnecessary copies of ACLs that could otherwise be inherited:
ICACLS X:\ /RESET /T /C
Next, Set all the ACLs to inherit permission from their parents:
ICACLS X:\ /INHERITANCE:E /T /C
Finally, you can set the security explicitly on the drive "X:" security tab, and the permissions will simply be inherited throughout the filesystem.


text:
Q: in indices() function gives 'ORA-01722: invalid number' error I am creating an example that uses in indices function in hibernate HQL by following  hibernate documentation
The document has below HQL example:
from Show show where 'fizard' in indices(show.acts)

So I created an entity for Show with a list of acts in it like this:
@Entity
public class Show {
    @Id
    @GeneratedValue
    private int id;

    private String name;

    @ElementCollection
    private List<String> acts;

// Getters & Settters
}

When I try to execute the HQL mentioned in document then I got the exception as:
Exception in thread "main" org.hibernate.QueryException: unindexed collection before indices() [from Show show where 'fizard' in indices(show.acts)]

So to make the collection as indexed I updated my Show entity property acts like this:
@ElementCollection
@OrderColumn
private List<String> acts;

After this my program started throwing error as:
Hibernate: select show0_.id as id1_2_, show0_.name as name2_2_ from Show show0_ where 'fizard' in (select acts1_.acts_ORDER from Show_acts acts1_ where show0_.id=acts1_.Show_id)

ERROR: ORA-01722: invalid number

Oct 23, 2014 10:12:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
    at org.hibernate.loader.Loader.doQuery(Loader.java:909)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2553)
    at org.hibernate.loader.Loader.doList(Loader.java:2539)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
    at org.hibernate.loader.Loader.list(Loader.java:2364)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at AppTest.showData(AppTest3.java:44)
    at AppTest.main(AppTest3.java:29)
Caused by: java.sql.SQLSyntaxErrorException: ORA-01722: invalid number

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:884)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1167)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
    ... 16 more

Here is the program that I am working on:
To save data into DB I have below logic:
private static void saveData() {
        Session session = getSession();
        session.getTransaction().begin();

        List<String> acts = new ArrayList<String>();
        acts.add("fizard");
        acts.add("Lord of Rings");

        Show s = new Show();
        s.setName("One");
        s.setActs(acts);

        List<String> acts1 = new ArrayList<String>();
        acts1.add("Tales");
        acts1.add("Stories");

        Show s1 = new Show();
        s1.setName("Two");
        s1.setActs(acts1);

        session.save(s);
        session.save(s1);

        session.getTransaction().commit();
        session.close();
    }

Then to run the HQL I have below logic:
private static void showData() {
        Session session = getSession();
        session.getTransaction().begin();

        Query q = session
                .createQuery("from Show show where 'fizard' in indices(show.acts)");
        List<Show> result = q.list();
        System.out.println("result=" + result);
        for (Show p : result) {
            System.out.println(p.getName());
        }

        session.getTransaction().commit();
        session.close();
    }

Based on the error, I understand that I am trying to compare a String 'fizard' with indices which is a number. But as I am just following the official hibernate document, can someone please tell me how can I write a simple program using in indices function of hibernate.

A: you queried this:
Hibernate:
select show0_.id as id1_2_, show0_.name as name2_2_ from Show show0_
where 'fizard' in
(select acts1_.acts_ORDER from Show_acts acts1_ where show0_.id=acts1_.Show_id);
The sense is daubtable, but acts1_.acts_ORDER may be a numeric (eg number) column to get a result like this.


text:
Q: Formatting group_header text when using tbl_stack from gtsummary I am trying to use the tbl_stack function from the gtsummary package, but the output text from using the group_header argument looks too visually similar to the rest of the labels. Ideally I would like to format the text with either bold, underline, or change the size to make it clear that I am displaying a separate section. Is there any way to accomplish group_header text formatting in the gtsummary package?
In the below example (taken from this issue: https://github.com/ddsjoberg/gtsummary/issues/669), I would ideally like the words "Demographics" and "Lab Values" to be in bold.
library(gtsummary)

tt <-
  trial %>%
  select(trt, response, age) %>%
  tbl_summary(by = trt, missing = "no")

# stacking two tbl_summary objects with header between
tbl_stack(list(tt, tt), group_header = c("Demographics", "Lab Values"))

A: Those kind of style changes are available within the {gt} package.  Convert the {gtsummary} table to {gt} using as_gt(), then make use of the {gt} styling functions. Example bolding below!
library(gtsummary)

tt <-
  trial %>%
  select(trt, response, age) %>%
  tbl_summary(by = trt, missing = "no")

# stacking two tbl_summary objects with header between
tbl_stack(list(tt, tt), group_header = c("Demographics", "Lab Values")) %>%
  as_gt() %>%
  gt::tab_style(
    style = gt::cell_text(weight = "bold"),
    locations = gt::cells_row_groups(groups = everything())
  )


text:
Q: Suppose $p$ and $p-2$ are both prime numbers where $p>5$. Prove $6$ divides $p-1$. Intuitively, any two prime numbers greater than five that have a non prime in between them is divisible by $6$. $6$ is between $5$ and $7$, $12$ is between $11$ and $13$, etc. But I have no idea how to represent this mathematically. A push in the right direction would be much appreciated.

A: Just a sketch for intuition:
All even numbers (besides 2) are non prime so $p - 1$ is divisible by 2.
One of $p - 2$, $p - 1$, $p$ are divisible by 3, we know $p$ and $p - 2$ are not, so $p - 1$ must be.
If $p - 1$ is divisible by 2 and 3, then $p - 1$ is divisible by 6.

A: You are essentially being asked to prove that $p-1\equiv0\mod{6}$.
You also know that the only possible residues$\mod{6}$ are $0,1,2,3,4,5$, or more conveniently $0,\pm1,\pm2,3$. If you think about the divisibility of numbers of the forms $6k, 6k\pm1,6k\pm2,6k+3$, you will find that only certain of them can possibly be primes. Note that since $p>5, k\ge1$.
Now try letting your number $p-1$ have various residues $\mod{6}$ and see what residues both $p$ and $p-2$ have as a consquence, and decide what that means about their primality. Then conclude what constraints that puts on $p-1\mod{6}$.

A: Suppose $p$ is of the form $6k + 3$, that is, $p \equiv 3 \bmod 6$.
Then $p$ must be $-3$ or $3$. But you said $p > 5$. So how about $p \equiv 5 \bmod 6$?
But again, you said, $p > 5$, so $p - 2$ is divisible by $3$ and at least one other prime (or one other instance of $3$). That leaves the case $p \equiv 1 \bmod 6$.
I ended each of the previous paragraphs with $6$. Mwahahahahaha!

A: Hint:  Give $k$ consecutive numbers, one of them is divisible by $k$.
.....

 So given $p-2, p-1, p$ one of them is divisible by $3$.  And one or more of them is divisible by $2$.

and

 But $p$ and $p-2$ are both prime and larger than $3$ so... it's not them.

.....

 So $p-1$ must be the one that is divisible by $3$ and $p-1$ must be the one that is divisible by $2$.  So $p-1$ is divisible by both $3$ and by $2$ so it is divisible by $6$.


text:
Q: Imageresizer : cropping square with maximum image width I'm trying to get Imageresizer to crop my image as a square and maintain the maximum possible width(I don't want to set the width or height to resize the image).
For example if I have an image with the size of 600x400px the larges possible square is 400x400px or if the image is 812x423 it should be 423x423px after cropping. How can I make it happen?
In the documentation I only find instruction on how to crop an image when specify the desired width and height: example, width=100&height=100&crop=auto.


text:
Q: How to get SVG element dimensions in FireFox? In most browsers, the following would work.
window.onload = function(){
    console.log( document.getElementById('svgElm').getBoundingClientRect().width );
};

Here is a demo. If you try it in Google Chrome, the console will output 200. However, FireFox returns 0.

A: I've ended up falling back to the parent dimensions if SVG properties cannot be returned. Here  is a demo http://jsbin.com/uzoyik/1/edit.
The relavent code is:
svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight

A: This Firefox bug was fixed in Firefox 33 which was released on 14 October 2014.
See bug 530985 for details.

A: The solution I found for this was to use .getComputedStyle(). And since svg elements are not supported in old IE8- browsers, .getComputedStyle() is the way to give consistent results.
So I ended up using this function in my library:
var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) {
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

A: I don't think "width" is a standard cross-browser property of the object returned by the  getBoundingClientRect method. I typically do something like:
var box = el.getBoundingClientRect();
var width = box.right-box.left;
var height = box.bottom-box.top;


text:
Q: USB 3 write speed fluctuates in Windows 10 I am using a 1TB SSD drive for file transfer between two Windows 10 computers that i connect using a USB 3 adapter and ports.
I copy files from System A to the drive and then from the drive onto System B.
I've performed one transfer from A to SSD to B at relatively constant rate of 180 MB/s. Once i've emptied the drive onto System B i needed to perform another transfer from System A to the drive and the speed of writing from A to SSD started to fluctuate similar to this:
USB random write speed
If the first transfer was fine then it is not a hardware limitation. Could there be a process in Windows that affects cache on an SSD/USB drive ?
One thing to note is when plugging the SSD thorough USB into System A for the second transfer it did show a second 0.5 GB drive called System Recovery that i did not create. Could this be a symptom of what could be causing it?
If not, is there a way to flush the SSD cache ?

A: You ignored two possible bottlenecks:

*

*You successfully kept the type of drive of your system A a secret. If the drive is a hard disk drive you might deal with defragmentation and files of varying size in system A which could heavily affect transfer rates.

*

If the first transfer was fine then it is not a hardware limitation.

Wrong. Once your SSD is filled up the write process on the SSD will slow down due to the necessary time-expensive erase functions. Your SSD firmware cannot react as fast in erasing as the operating system sends TRIM commands to the drive when you are deleting the content of your transfer SSD to be able to copy another round of data on it.


text:
Q: For Looping Over Dictionary Object I have a Python dictionary with the following form:
data = {'2022-01-01': [123, 456], '2022-01-02': [789, 120], ... }

I am trying to loop over the dictionary data and divide the two numbers contained in the lists (e.g. 123/456, 789/120, etc.) with the following:
for values in len(range(data)):
    ratio = values[0]/values[1]

But I get a TypeError saying that the dict object cannot be interpreted as an integer. My numbers are clearly integers. Is this not the correct way to loop across a dictionary?
Also, is there a way that I can store the resulting ratio along with the dates in either a new dictionary or a pandas data frame?

A: data is a dictionary, not a function, so you shouldn't use parenthesis to attempt to access it.
You should also be iterating over data.items(), not len(range(data)). You're iterating over the keys of a dictionary, not a list.
With these two corrections, we get the following:
for key, values in data.items():
    ratio = values[0]/values[1]

A: Also worth mentioning:
len(range(data)) is just a number. for key, value in 123 (for instance) does not make sense. To iterate the key, value pairs of a dictionary (named data), you need to do for key, value in data.items().
You don't need the keys in order to produce your desired output, so there's no need to iterate the key, value pairs, just the values. To iterate just the values, do for value in data.values().


text:
Q: " import telegram.ext ModuleNotFoundError: No module named 'telegram.ext'; 'telegram' is not a package" after installing python-telegram-bot Hey I was trying to edit a telegram bot, but this error keeps coming:
import telegram.ext ModuleNotFoundError: No module named 'telegram.ext'; 'telegram' is not a package.
My code is like this:-
import telegram.ext

with open('token.txt', 'r') as f:
    TOKEN = f.read()

def start(update, context):
    update.message.reply_text("Helllo")

updater = telegram.ext.Updater(TOKEN, use_context=True)
disp = updater.dispatcher

any help will be appreciated
I've tried reinstalling python-telegram-bot.

A: Probably you've installed a wrong telegram package, too. Some IDEs install packages automatically and they install telegram instead of python-telegram-bot.
You should find the wrong installed package and uninstall it.
Figure out what package is imported on import telegram.ext, you can find it in the error description. Then you should uninstall it, using a command like this:
pip uninstall telegam

Then install python-telegram-bot if it is not installed:
pip install python-telegram-bot


text:
Q: 2 x 2 mixed anova? 96 participants were randomly assigned to one of the two groups regardless of their motivation level. Participants in both the groups were exposed to both the experimental conditions of gain framed messages and loss framed messages. The only difference was - counterbalancing such that the participants were shown gain frame message in group 1 then its corresponding loss frame message was shown in group 2.
So here the within group factor is: framing condition - gain frame and loss frame
between group factor means that this should vary across two groups but in my study both participants of high and low motivation were present in both groups and exposed to both gain frame and low frame messages.
Participants in two groups were different but exposed to same but counterbalanced design.
I am not sure if this is a 2 x 2 mixed anova design with framing condition as within group and motivation as between group factor.

A: You conducted a crossover study. The proper analysis method is a bit tricky, and it will depend on what are you willing to assume about period effect (maybe the second response always tends to be lower) and carryover (maybe the effect of the first intervention lingers to affect the second answer).


text:
Q: somar valores de uma tabela e colocar o resultado em outra Possuo uma tabela chamada players e preciso somar os valores da coluna pontos mas somente das que possuírem o mesmo account_id e após colocar o resultado em outra tabela chamada accounts justamente na qual possuir o id indicado. O resultado seria esse:
Tabela players:
account_id    |pontos
1             |50
1             |100
2             |25
2             |20

Tabela accounts:
id            |pontos
1             |150
2             |45

A: tente isso:
INSERT INTO accounts values (select account_id as id, SUM(pontos) from players group by account_id);


text:
Q: Get rid of rogue fold/unfold behavior in Visual Studio A fold is the region of the file that's enclosed by the line and hash marks topped by a + or - icon between the file contents and the line numbers. I believe the misunderstanding comes from me using Notepad++'s term for this feature.
I'm editing a .css file and am not sure how this fold appeared at the end of my file. I can't get rid of it because it's not associated with a brace or region. I assumed there was a whitespace character creating it, so I tried showing whitespace characters with Ctrl+R, Ctrl+W but nothing showed up relating to it. Now, every time I add new lines to the end of the file this fold gives me the option to fold from that arbitrary line through the rest of the file, even if new braces and regions are added with their own folds.
I also found this question's answer that suggests turning the Outlining off, but there's two problems with that:

*

*It turns Outlining off the the entire file.

*It hides the problem because when the file is reopened, the rogue fold appears again.

No new line at the end of the file, so nothing to fold:

The fold consuming the end of the file:

Continues consuming the end of the file even with new fold groups:

With some cuts, newlines, and deletes, I can move the fold up the file:

With some similar manipulations, I can move the fold back to the end of the file:

No matter what I do though, I can't remove the fold. Backspacing and deleting from the state in the last pic only moves the fold back up the file and will reappear when newlines are added at the end.
Edit 2: I found another one of the rogue folds on another #region tag higher in the file. These 2 folds only exist in this file as all my other .css files display their regions correctly.
I've also double checked these files in Notepad++, and it properly shows all foldable regions enclosed by curly braces, #region appears to be a Visual Studio format effect.
Edit 3: I've now discovered another rogue fold in an .html file that was occupying the same lines as a div (html elements act as their own curly brace sections). The strange thing about this one is that it doesn't consume the rest of the file. Instead it's hiding everything between two completely blank lines (after I moved it out of the div), which I suspect is what the other 2 mentioned in my previous edits are also doing, but I can't detach their ends from the end of file (for obvious reasons).


text:
Q: I can't access my variables from another class I am working on a simple Bingo game that has randomized numbers. My main class (Bingo) is here:(note that I have more code that is not relevant to the problem)`
public class Bingo {
    public static void main (String[] args) {
        RandNum columnB = new RandNum();
        columnB.max = 15;
        columnB.randNum();
        int b1 = columnB.row1;
        int b2 = columnB.row2;
        int b3 = columnB.row3;
        int b4 = columnB.row4;
        int b5 = columnB.row5;

        RandNum columnI = new RandNum();
        columnI.min = 16;
        columnI.max = 30;
        columnI.randNum();
        int i1 = columnI.row1;
        int i2 = columnI.row2;
        int i3 = columnI.row3;
        int i4 = columnI.row4;
        int i5 = columnI.row5;

        RandNum columnN = new RandNum();
        columnN.min = 31;
        columnN.max = 45;
        columnN.randNum();
        int n1 = columnN.row1;
        int n2 = columnN.row2;
        int n3 = columnN.row3;
        int n4 = columnN.row4;
        int n5 = columnN.row5;

        RandNum columnG = new RandNum();
        columnG.min = 46;
        columnG.max = 60;
        columnG.randNum();
        int g1 = columnG.row1;
        int g2 = columnG.row2;
        int g3 = columnG.row3;
        int g4 = columnG.row4;
        int g5 = columnG.row5;

        RandNum columnO = new RandNum();
        columnO.min = 61;
        columnO.max = 75;
        columnO.randNum();
        int o1 = columnO.row1;
        int o2 = columnO.row2;
        int o3 = columnO.row3;
        int o4 = columnO.row4;
        int o5 = columnO.row5;
    }
}

My class that I am using to generate the random numbers:
public class RandNum {
    int min = 1;
    int max;

    public void randNum() {
        Random rn = new Random();

        int row1 = rn.nextInt(max - min + 1) + min;
        int row2 = rn.nextInt(max - min + 1) + min;
        int row3 = rn.nextInt(max - min + 1) + min;
        int row4 = rn.nextInt(max - min + 1) + min;
        int row5 = rn.nextInt(max - min + 1) + min;
    }
}

Now the issue is that I am trying to set my b1, b2, etc variables to the variable row1, etc. in the RandNum class. I know that I could just put it all in one class but this is a problem I have had multiple times so I'd like to solve it. Any help is much appreciated.

A: Your b etc. variables are scoped to the main method of Bingo so you'll never be able to access them from another class - or another method of the same class for that matter.
You could set them as public static fields of Bingo instead of declaring them within the method's body (or privates with getters), but due to the number of variables you have here, I suggest refactoring first and investigating a few data structures such as Collections and Maps.

A: What happens is that you are declaring rowX variables as local variables in your randNum() method.
This makes that its scope is only that method, so they won't exist / be available outside it.
What can you do?
Declare them as class attributes:
public class RandNum {
    int row1, row2, row3, row4, row5;
    ...
    public void randNum() {...}
}

Note: You could use an array instead:
int[] rows = new int[5];

Then in your method:
public void randNum() {
    Random rn = new Random();

    for (int i = 0; i < rows.length(); i++)
        rows[i] = rn.nextInt(max - min + 1) + min;
}

A: This should solve it. The variables b1,b2,... are local to your randNum function and will be out of scope once execution exits the function. The solution is to store the variables in a field in the RandNum class.
public class RandNum{
    private int[] rows = new int[5];
    private int min;
    private int max;

    public RandNum(int min, int max) {
        Random rn = new Random();
        for(int i=0;i<5;++i)
           rows[i] = rn.nextInt(max - min + 1) + min;
    }

    public int getRow(int row) {
       return rows[i];
    }
}

public static void main (String[] args) {
    RandNum columnB = new RandNum(1,15);
    int b1 = columnB.getRow(0);
    int b2 = columnB.getRow(1);
    int b3 = columnB.getRow(2);
    int b4 = columnB.getRow(3);
    int b5 = columnB.getRow(4);

    ...
}

A: See: Why use getters and setters?
Create accessors/mutators:
public class RandNum {
    private int min;
    private int max;

    public RandNum(int min, int max) {
        setMin(min);
        setMax(max);
    }

    public RandNum() {
        this(1, 0);
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

    public void setMin(int min) {
        this.min = min;
    }

    public void setMax(int max) {
        this.max = max;
    }

    // ...
}

Then use them:
public class Bingo {
    public static void main (String[] args) {
        RandNum columnB = new RandNum();
        columnB.setMax(15);
        // ...
    }
}


text:
Q: v2 Azure Function with Service Bus trigger not firing I am using Azure Functions V2 with a Service Bus trigger using 1.0.23 of the C# Functions SDK. I'm using the following approach to get secrets from KeyVault and use them within the settings of the triggers: How to map Azure Functions secrets from Key Vault automatically
The function, especially when it has done nothing for a while, doesn't fire when there are messages on the subscription. If I then go to the portal and execute manually (yes, that particular execution is fired with a null message) it kicks it into life and picks up the other messages on the queue and processes them correctly.
This obviously isn't ideally for our automated tests. Has anybody seen this, or know of anything that will help?
Also, the Function App is running on a consumption plan.

A: App Service Plan
If you're using App Service plan then it's simple, just make use of Always on
Consumption Plan
If you're using Consumption plan, the issue could be that your triggers did not sync properly with the Azure Infrastructure (Central Listener). It could have happened due to the way you deployed/edited your trigger related settings as explained in issue #210 below.
When you access the function directly from Portal, it might be forcing your function app to come alive, but as you can see that's only a workaround. Something similar is mentioned here
Take a look at these issues:

*

*Service Bus Topic Trigger goes to sleep - Consumption Plan
They also mention that it wakes up only on accessing it via the portal or calling a HTTP triggered function in the same app, which is similar to the behavior you are seeing.

*Issue #210

*Issue #681
There are 3 suggested ways to resolve it, mentioned as part of Issue #210 above

In order to synchronize triggers when these deployment options are
  used, open the Azure Portal and click the Refresh button, or make a
  API call to the sync triggers endpoint:
  https://github.com/davidebbo/AzureWebsitesSamples/blob/master/ARMTemplates/FunctionsWebDeploy.json#L90
Powershell sample:
  https://github.com/davidebbo/AzureWebsitesSamples/blob/master/PowerShell/HelperFunctions.ps1#L360-L365

A: I've had a similar issue. ServiceBus connection was injected using ServiceBus value in ConnectionStrings section of Function configuration. This is enough when Function is in hot state but after transitioning to cold state AzureWebJobsServiceBus value is used to connect to service bus. So in my case setting AzureWebJobsServiceBus to ServiceBus connection string in Function configuration fixed this.


text:
Q: Line trimed to .. in gfsh command I am running the below command in Unix box, it is gfsh command:
$GEMFIRE_HOME/bin/gfsh -e "connect --locator=$HOST[22710]" -e "list members" | grep "coordinator"

but, the catch is, if the returned members contain more than 100 characters then the output is .. for them , like below:
locator:103268:locator)<ec><v87><coordinato..

so the grep is failing. We know that we can change grep pattern, but we want to grep particular coordinator only.
Why does the output line get trimmed to ..?
I searched the docs, found below.
https://gemfire.docs.pivotal.io/91/geode/tools_modules/gfsh/configuring_gfsh.html

gfsh commands such as query produce output with wide columns that may
  become misaligned and require manual reformatting to view the output.
  If the output cannot fit in the available width of the terminal, gfsh
  automatically trims the columns widths to fit. You can disable this
  behavior by setting the gfsh environment variable GFSH.TRIMSCRWIDTH to
  false.

Any suggestions?
I tried to get the only second pattern by awk '|', but still, the coordinator was a coordinator.
Tried cut also, didn't work.
$GEMFIRE_HOME/bin/gfsh -e "connect --locator=$HOST[22710]" -e "list members" | awk -F'|' '{print $2}'

103268:locator)<ec><v87><coordinato..

$GEMFIRE_HOME/bin/gfsh -e "connect --locator=$HOST[22710]" -e "list members" | awk -F'|' '{print $2}'

should be able to grep "coordinator" the output of gfsh and the output should not have .. in the lines.

A: If you add the following to your gfsh command, you should see the full output:
-e "set variable --name=APP_RESULT_VIEWER --value=x"

This is a workaround - the value x is arbitrary and this just avoids the default behavior you're seeing.


text:
Q: Python parsedatetime: get current month / first of the month I'm using the parsedatetime library in my Python script and it appears that "last month" works and "next month" but not "this month."
What am I missing? Is there a way to get the first day of the current month?
Edit:
Sorry, here's some code:
import parsedatetime.parsedatetime as pdt
p = pdt.Calendar()
res = p.parse('this month')
print(str(res))

Returns:
(time.struct_time(tm_year=2015, tm_mon=7, tm_mday=13, tm_hour=16, tm_min=22, tm_sec=10, tm_wday=0, tm_yday=194, tm_isdst=0), 0)

A: I've never used parsedatetime for this though that's an interesting way to get the first of the month.  Still, I generally do this:
>>> datetime.datetime.now().replace(day=1, hour=0, minute=0, second=0)

It's less wasteful of resources, too, since you don't have to parse any text at runtime, but that's an aside, really.
You can convert this to a time.struct_time via timetuple():
>>> datetime.datetime.now().replace(day=1, hour=0, minute=0, second=0).timetuple()

time.struct_time(tm_year=2015, tm_mon=7, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=182, tm_isdst=-1)

A: I know it's been time to this question but I would like to share the trick I found as parsedatetime does not have bom nor bow
I have used the following sneaky trick to get upper bound for current month and the upper bound for the current week like this
res = p.parse("one month after last month") returns the start of the current month
res = p.parse("one week after last week") returns the start of the current week


text:
Q: Detect error from clean_fieldname in django template class MyForm(forms.Form):
   ....

    def clean_myfield(self):
        ....
        ....
            raise forms.ValidationError("Wow error!")
        return myfield

How can I add "if statment" in Django Template if this error(from clean_myfield) exist?
{% if error_from_clean_myfield %}
   ......
{% endif %}

A: You should check the variable:
{{ form.myfield.errors }}

Have a look at the documentation.


text:
Q: get seleceted dropdown option value jquery I have two dropdowns -- for the month and year -- and a button. When the user clicks the button, I want to grab the selected month value and year value and pass them as query string to a URL like this: https://mysite.com/events.aspx?my=may2012.
How do I grab those values using jQuery or Javascript?

        <select>
            <option selected="selected">September</option>
        <option>August</option>
        <option>July</option>
        <option>June</option>
        <option>May</option>
        <option>April</option>
        <option>March</option>
        <option>February</option>
        <option>January</option>
        <option>December</option>
        <option>November</option>
        <option>October</option>
        </select>

        <select>
            <option selected="selected">2012</option>
            <option>2013</option>
            <option>2014</option>
        <option>2015</option>
        </select>

    GO

A: I'm assuming you want this all to happen on the click event of btnBlue.
Start with a click handler...
$('a.btnBlue').click(function() {
   // ...
});

Then get the values of the month/year...
var month = $('.inpMonth select').val();
var year = $('.inpYear select').val();

Then navigate to that URL...
window.location.href = 'https://mysite.com/events.aspx?my=' + month + year;

All together that's...
$('a.btnBlue').click(function() {
    var month = $('.inpMonth select').val();
    var year = $('.inpYear select').val();
    window.location.href = 'https://mysite.com/events.aspx?my=' + month + year;
});

A: There is a mistake in T. Stone's answer. the selector should have a dot.
Other than that - great answer!
See my fiddle

A: first, get references to your SELECT and LINK dom objects:
var button = $('a.btnBlue');
var month = $('#datepicker .inpMonth select');
var year = $('#datepicker .inpYear select');

next, create a function to return the current month & year as a string:
function currentSelection() {
  return month.val() + year.val();
}

create a function which navigates you to the new url based on currentSelection():
function navigateToDate() {
  window.location.href = "https://mysite.com/events.aspx?my=" + currentSelection();
}

when the button is clicked, call navigateToDate():
button.click( navigateToDate );

A: To get the month try
$(".inpMonth select").val();

To parse a whole form give .serialize() and .serializeArray() a try
$("form").serialize()


text:
Q: using case for multiple parameters in where condition using sql I have a query as below. I want to return the case value for each filename(alter.pdf, modify.pdf) in rows.
However I am getting only case value for alter.pdf.
SELECT CASE WHEN COUNT(P.[packageid]) > 0 THEN 1 ELSE 0 END AS [VALUE]
              FROM [Table_1] AS P
              INNER JOIN
       [Table_2] AS F on F.FileID = P.FileID
        WHERE F.FileName IN('alter.pdf','modify.pdf')

A: I think you are looking for something like this:
SELECT  F.[FileName]
        , sum(CASE WHEN F.FileName = 'alter.pdf' THEN 1
               WHEN F.FileName = 'modify.pdf' THEN 1
               ELSE 0
          END AS) [VALUE]
FROM [Table_1] AS P
INNER JOIN [Table_2] AS F on F.FileID = P.FileID
WHERE F.FileName IN('alter.pdf','modify.pdf')
group by F.[FileName]


text:
Q: Can I make icons smaller on a bq Aquaris e5 Ubuntu Edition? It's all on the title
But I need more characters...

A: I just went through the entire ubuntu-phone mailing list if anyone ever brought up making icons smaller and: nope …
Sorry to be the harbinger of bad news!