Q:

Laravel: General error: 1615 Prepared statement needs to be re-prepared

I'm using last version of laravel (5.1) in a homestead virtual machine (vagrant).
I connect my project to a local mariaDB server, in which I have some table and 2 db-view.
Since I made some select only on the db-view tables, I receive back randomly this error:

General error: 1615 Prepared statement needs to be re-prepared

From today, I always get this error when made select only on the db views.
If I open my phpMyAdmin and make the same select it return the correct result.
I tried to open php artisan tinker and select one record of the db-view but it return the same error:
// Select one user from user table
>>> $user = new App\User
=> <App\User #000000006dc32a890000000129f667d2> {}
>>> $user = App\User::find(1);
=> <App\User #000000006dc32a9e0000000129f667d2> {
       id: 1,
       name: "Luca",
       email: "luca@email.it",
       customerId: 1,
       created_at: "2015-08-06 04:17:57",
       updated_at: "2015-08-11 12:39:01"
   }
>>>
// Select one source from Source db-view
>>> $source = new App\Source
=> <App\Source #000000006dc32a820000000129f667d2> {}
>>> $source = App\Source::find(1);
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared (SQL: select * from `sources` where `sources`.`id` = 1 limit 1)'

How can I fix that?
I read about a problem with mysqldump (but not in my case) and to increase value of table_definition_cache but it is not sure that it will work and I can't modify them.
Is this a kind of laravel bug?
How can I figure that out?

Edit:
As asked, I add my model source code.
Source.php:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Source extends Model
{
    protected $table = 'sources';

    /*
    |--------------------------------------------------------------------------
    | FOREIGN KEYS
    |--------------------------------------------------------------------------
    */

    /**
     *
     * @return [type] [description]
     */
    public function customersList(){
        return $this->hasMany("App\CustomerSource", "sourceId", "id");
    }

    /**
     *
     * @return [type] [description]
     */
    public function issues(){
        return $this->hasMany("App\Issue", "sourceId", "id");
    }
}

Edit 2:
If I execute the same query in the project with mysqli it works:
$db = new mysqli(getenv('DB_HOST'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'), getenv('DB_DATABASE'));
if($db->connect_errno > 0){
    dd('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * FROM `sources` WHERE `id` = 4";
if(!$result = $db->query($sql)){
    dd('There was an error running the query [' . $db->error . ']');
}

dd($result->fetch_assoc());

EDIT 3:
Afeter 2 month, I'm still there. Same error and no solution found.
I decide to try a little solution in aritsan tinker but no good news.
I report what I've tried:
First try to fetch a table model:
>>> $user = \App\User::find(1);
=> App\User {#697
     id: 1,
     name: "Luca",
     email: "luca.d@company.it",
     customerId: 1,
     created_at: "2015-08-06 04:17:57",
     updated_at: "2015-10-27 11:28:14",
   }

Now try to fetch a view table model:
>>> $ir = \App\ContentRepository::find(15);
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbname.content_repositories' doesn't exist (SQL: select * from `content_repositories` where `content_repositories`.`id` = 1 limit 1)'

When contentRepository doesn't have correct table name setup inside the model ContentRepository.php:
>>> $pdo = DB::connection()->getPdo();
=> PDO {#690
     inTransaction: false,
     errorInfo: [
       "00000",
       1146,
       "Table 'dbname.content_repositories' doesn't exist",
     ],
     attributes: [
       "CASE" => NATURAL,
       "ERRMODE" => EXCEPTION,
       "AUTOCOMMIT" => 1,
       "PERSISTENT" => false,
       "DRIVER_NAME" => "mysql",
       "SERVER_INFO" => "Uptime: 2513397  Threads: 12  Questions: 85115742  Slow queries: 6893568  Opens: 1596  Flush tables: 1  Open tables: 936  Queries per second avg: 33.864",
       "ORACLE_NULLS" => NATURAL,
       "CLIENT_VERSION" => "mysqlnd 5.0.11-dev - 20120503 - $Id: id_here $",
       "SERVER_VERSION" => "5.5.5-10.0.17-MariaDB-1~wheezy-wsrep-log",
       "STATEMENT_CLASS" => [
         "PDOStatement",
       ],
       "EMULATE_PREPARES" => 0,
       "CONNECTION_STATUS" => "localiphere via TCP/IP",
       "DEFAULT_FETCH_MODE" => BOTH,
     ],
   }
>>>

CHANGE TABLE VALUE INSIDE model ContentRepository.php:
>>> $ir = \App\ContentRepository::find(15);
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared (SQL: select * from `contentRepository` where `contentRepository`.`id` = 15 limit 1)'

When it is correct, pay attention to "errorInfo" that is missing:
>>> $pdo = DB::connection()->getPdo();
=> PDO {#690
     inTransaction: false,
     attributes: [
       "CASE" => NATURAL,
       "ERRMODE" => EXCEPTION,
       "AUTOCOMMIT" => 1,
       "PERSISTENT" => false,
       "DRIVER_NAME" => "mysql",
       "SERVER_INFO" => "Uptime: 2589441  Threads: 13  Questions: 89348013  Slow queries: 7258017  Opens: 1604  Flush tables: 1  Open tables: 943  Queries per second avg: 34.504",
       "ORACLE_NULLS" => NATURAL,
       "CLIENT_VERSION" => "mysqlnd 5.0.11-dev - 20120503 - $Id: id_here $",
       "SERVER_VERSION" => "5.5.5-10.0.17-MariaDB-1~wheezy-wsrep-log",
       "STATEMENT_CLASS" => [
         "PDOStatement",
       ],
       "EMULATE_PREPARES" => 0,
       "CONNECTION_STATUS" => "localIPhere via TCP/IP",
       "DEFAULT_FETCH_MODE" => BOTH,
     ],
   }

Show db's tables:
>>> $tables = DB::select('SHOW TABLES');
=> [
     {#702
       +"Tables_in_dbname": "table_name_there",
     },
     {#683
       +"Tables_in_dbname": "table_name_there",
     },
     {#699
       +"Tables_in_dbname": "table_name_there",
     },
     {#701
       +"Tables_in_dbname": "table_name_there-20150917-1159",
     },
     {#704
       +"Tables_in_dbname": "contentRepository", */ VIEW TABLE IS THERE!!!! /*
     },
     {#707
       +"Tables_in_dbname": "table_name_there",
     },
     {#684
       +"Tables_in_dbname": "table_name_there",
     },
   ]

Try with normal select:
>>> $results = DB::select('select * from dbname.contentRepository limit 1');
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared (SQL: select * from dbname.contentRepository limit 1)'

Try unprepared query:
>>> DB::unprepared('select * from dbname.contentRepository limit 1')
=> false

Try second time unprepared query:
>>> DB::unprepared('select * from dbname.contentRepository limit 1')
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: select * from dbname.contentRepository limit 1)'

Try PDOStatement::fetchAll():
>>> DB::fetchAll('select * from dbname.contentRepository limit 1');
PHP warning:  call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'fetchAll' in /Users/luca/company/Laravel/dbname/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php on line 296

Try second PDOStatement::fetchAll():
>>> $pdo::fetchAll('select * from dbname.contentRepository limit 1');
  [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to undefined method PDO::fetchAll()

Try statement... :
>>> $pdos = DB::statement('select * from dbname.contentRepository limit 1')
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared (SQL: select * from dbname.contentRepository limit 1)'

Thank you

A:

It seems to work adding
'options'   => [
                \PDO::ATTR_EMULATE_PREPARES => true
            ]

Inside projectName/config/database.php file in DB configuration. It will be like this:
'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'forge'),
    'username'  => env('DB_USERNAME', 'forge'),
    'password'  => env('DB_PASSWORD', ''),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
    'options'   => [
        \PDO::ATTR_EMULATE_PREPARES => true
    ]
],

Laravel 5.1. Hope it will help!

A:

As per the comments in the accepted answer,
running
SET GLOBAL table_definition_cache = 1024
in the MariaDB solved the problem.
https://mariadb.com/kb/en/library/server-system-variables/#table_definition_cache


Q:

Scheduler in clustered environment

Our (Spring) application contains several Schedulers which become active during the night to change/update some data (from Database) in Batch.
This is all running fine, the problem is that our application will soon run in a clustered environment.
What are the best options to prevent a scheduler of instance A and instance B are doing the same work at the same time?
** UPDATE **

Clustered environment is setup as 'active-active'.
Each node communicates with it's own database instance. Each database instance will replicate data to the other instances.
DB-instances are not setup as 'master-slave' but will run in a Galera cluster where each instance executes insert-update-delete operations.
So each scheduler should run only once on one instance. The other instances should not run the schedulers. So I need to find a way the a Scheduler of one instance runs, the same schedulers of the other instances should not run.

A:

Just for completeness: we ended up with persistent Quartz job scheduling.
This post helped me a lot about persistent Quartz scheduling with Spring.


Q:

Regular Expression Returns Undefined

I'm attempting one of the beginner coderByte challenges, Simple Symbols.  Challenge summary below.
"Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter."
function SimpleSymbols(str){
  var RegExp = /\+\w\+/gi;
  var regexp1 = /^\w/gi;
  var regexp2 = /\w$/g;

  if(regexp1.test(str) == true){
    return false
  } else if(regexp2.test(str) == true){
    return false
  } else if(RegExp == true){
    return true
  }

}

console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));

The first regular expression I'm testing, /^\w/gi, comes back undefined, and I can't figure out why?
https://regex101.com/ is a great tool I've used before, and my expression does identify f as the first character in the string, but when I test it in codepen, it comes back undefined in the console.

A:

Code
See regex in use here
^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$

Alternatively, using the opposite logic (catching invalid strings instead of valid ones), you can use (?:^|[^+])[a-z]|[a-z](?:[^+]|$)
Usage
Please note the valid/invalid strings below have been created according to the OP's explanation of valid and invalid strings: That each letter must be surrounded by a + symbol. and that the plus sign + may be shared between characters such that +a+a+ is valid (specified in comments below the question).

var a = [
  // valid
  "++d+===+c++==+a++",
  "+a+a+a+",
  "+a++a+",
  "+a+",
  // invalid
  "++d+===+c++==a",
  "+=d+",
  "+dd+",
  "+d=+",
  "+d+d",
  "d+d+"
];
var r = /^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$/mi;

a.forEach(function(s){
 console.log(r.test(s));
});

Explanation

^ Assert position at the start of the line
[+=\d]* Match any number of characters in the set (+, =, or digit)
\+ Match a literal plus sign +
(?:[a-z]\+[+=\d]*)+ Match one or more of the following

[a-z] Match a lowercase ASCII letter
\+ Match a literal plus sign +
[+=\d]* Match any number of characters in the set (+, =, or digit)

$ Assert position at the end of the line


Q:

How to change The theme of Windows form application in C#

I am trying to get rid of the default theme of window form application and want to changed it to be better look one in C# I have searched in google but found no result.
Is there any library which I use  to make a good look window form application?
If there is would you please share the link with me.
thanks in advance.

A:

I had this need and I found the Metroframework library.
https://www.nuget.org/packages/MetroFramework/
with few changes you will have a good change in the visual.
after install go to designer class and modify this:
public partial class frmTeste : form

to:
public partial class frmTeste : MetroForm

and you will see the diference.


Q:

Can a public IP address be used as Google OAuth redirect URI?

I'm trying to set a web service that needs the user's Google Latitude info, so I'm using Google OAuth to get the user authorization stuff.
However, when trying to set the redirection URI in the Google APIs Console for a web application client ID I get a message error if I try to set it to 'http://PUBLIC_IP/'.
I need to test it with non local users (thus localhost can't be used), so I would like to know if having a web domain is mandatory in order to use Google's OAuth. If not, how can I solve this issue?

A:

This is not currently supported. I filed a feature request and will update on progress.

A:

You can use xip.io to work around it.
For example:  '192.168.0.50.xip.io:3000' will resolve to '192.168.0.50:3000'

A:

I ran into this issue too and so I entered a URL with a .com extension and also entered it into my /etc/hosts file. Works like a charm.
It totally sucks that my entire app now has to be developed on an apparently 'live' domain though.


Q:

oracle external table with date column and skip header

I have a file,
ID,DNS,R_D,R_A
1,123456,2014/11/17,10
2,987654,2016/05/20,30
3,434343,2017/08/01,20

that I'm trying to load to oracle using External Tables. I have to skip the header row and also load the date column.
This is my query:
DECLARE
FILENAME VARCHAR2(400);
BEGIN
FILENAME := 'actual_data.txt';
EXECUTE IMMEDIATE 'CREATE TABLE EXT_TMP (
  ID      NUMBER(25),
  DNS  VARCHAR2(20),
  R_D DATE,
  R_A  NUMBER(25)
)
ORGANIZATION EXTERNAL (
  TYPE ORACLE_LOADER
  DEFAULT DIRECTORY USER_DIR
  ACCESS PARAMETERS (
    RECORDS DELIMITED BY NEWLINE
    FIELDS TERMINATED BY '',''
    MISSING FIELD VALUES ARE NULL
    SKIP 1
    (
  "ID",
  "DNS",
  "R_D" date "dd-mon-yy",
  "RECHARGE_AMOUNT"
    )
  )
  LOCATION (''' || FILENAME || ''')
)
PARALLEL 5
REJECT LIMIT UNLIMITED';
END;

I get following exception:
ERROR at line 1:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error
KUP-00554: error encountered while parsing access parameters
KUP-01005: syntax error: found "skip": expecting one of: "column, exit, (,
reject"
KUP-01007: at line 4 column 5
ORA-06512: at "SYS.ORACLE_LOADER", line 19

I'm using sqlplus.
Could some oracle veterans please help me out and tell me what I'm doing wrong here? I'm very new to oracle.

A:

You don't want to create any kind of tables (including external ones) in PL/SQL; not that it is impossible, but it is opposite of the best practices.
Have a look at my attempt, based on information you provided - works OK.
SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> create table ext_tmp
  2  (
  3    id      number,
  4    dns     varchar2(20),
  5    r_d     date,
  6    r_a     number
  7  )
  8  organization external
  9  (
 10    type oracle_loader
 11    default directory kcdba_dpdir
 12    access parameters
 13    (
 14      records delimited by newline
 15      skip 1
 16      fields terminated by ',' lrtrim
 17      missing field values are null
 18      (
 19       id,
 20       dns,
 21       r_d date 'yyyy/mm/dd',
 22       r_a
 23      )
 24    )
 25    location ('actual_data.txt')
 26  )
 27  parallel 5
 28  reject limit unlimited;

Table created.

SQL> select * from ext_tmp;

        ID DNS                  R_D               R_A
---------- -------------------- ---------- ----------
         1 123456               17.11.2014         10
         2 987654               20.05.2016         30
         3 434343               01.08.2017         20

SQL>


Q:

A segment is removed from a semi circle what is the pdf of the remaining area?

Question:
Given the illustration below, the cdf of  Z is
\begin{equation}
Pr(Z\leq z) = \frac{\text{exp}(-\lambda A_z)-\text{exp}(-N/2)}{1-\text{exp}(-N/2)}
\end{equation}
How could one Prove that
\begin{equation}
f_z(Z) = \frac{2\lambda \sqrt{R^2-z^2}}{1-\text{exp}(-N/2)} \text{exp}[-\lambda A_z]
\end{equation}
for $0<z\leq R$
where $A_z$ = $R^2 [\cos^{-1} (z/R)- (z/R)\sqrt{1-(z/R)^2}]$
Challenge:
The first problem I have is understanding how $A_z$ was derived, then, how the numerator of the first equation of the pdf was gotten. The closest clue I have to $A_z$ is this question and this one, but here, the height of the segment here is unknown.
In case it might interest someone, $N = \lambda \pi R^2$ and $\lambda$ represents the density of a two dimensional Poisson Point Process

A:

I understand that you have already recognised that this problem can be solved by using the identity relating the PDF of a distribution to the CDF: $ f_Z(z) = F_Z'(z)$,
which for your particular CDF is equivalent to:
$$ f_Z(z) = \frac{-\lambda A'(z) \exp(-\lambda A(z))}{1- \exp(-N/2)}.$$
So it remains to calculate $A(z)$, and then use this to derive $A'(z)$.

Calculating A(z)
In the following I refer to my diagram (unfortunately not as well produced as your graphic, but you should get the point).
Let $\theta_z$ denote the angle made between $A \hat O B$, using the standard trigonometric identify for the cosine we have that
$$\theta_z = \cos^{-1}(z/R).$$
Therefore the area of the circular wedge with angle $2\theta_z$ (i.e. the wedge bounded by the lines $OB$ and $OC$) is
\begin{aligned}W_z &= \pi R^2 \times \frac{2\theta_z}{2 \pi} \\
& =  R^2 \theta_z \\
& = R^2 \cos^{-1}(z/R).
\end{aligned}
We can now obtain $A(z)$ by subtracting from $W_z$ the area, $T_z$, of the triangle made out by the lines $OBCO$, which is equal to the area of the rectangle with side lengths equal to those of the line segments $OA$ and $AB$.
Since $A$ has coordinates $(z,0)$ the line segment $OA$ has length $z$; we can calculate the coordinates  of $B$ by relying on the formula $x^2 + y^2 = R^2$, which gives coordinates $(z, \sqrt{R^2 - z^2})$, and so the length of $AB$ is $\sqrt{R^2 - z^2}$. Combining these we get
$$T_z = z \sqrt{R^2 - z^2}$$,
and further more
\begin{aligned}
A(z) &= W_z - T_z \\
& = R^2 \cos^{-1}(z/R) - z \sqrt{R^2 - z^2} \\
& = R^2 \left( \cos^{-1}(z/R) - (z/R) \sqrt{1 - (z/R)^2} \right),
\end{aligned}
which is as you gave in the question statement.

Calculating $A'(z)$
This now follows from appealing to standard identities for derivatives. If we denote
$$g(x) = \cos^{-1}(x) - x \sqrt{1 - x^2},$$
then we have $A(z) = R^2 g(z/R)$, and so using the chain rule:
\begin{aligned}
A'(z) & = R^2 \frac{d}{dz} g(z/R)  \\
& = R^2 g'(z/R) \frac{d}{dz} \left(\frac{z}{R}\right) \\
& = R g'(z/R).
\end{aligned}
So concentrating on $g(x)$ we differentiate this using the identity for the derivative of $\cos^{-1}$, as well as the product rule to handle the second term to obtain:
$$g'(x) = - \frac{1}{\sqrt{1-x^2}} - \frac{1-2x^2}{\sqrt{1-x^2}}, $$
where the first term above is contributed from $\cos^{-1}$, and the second is from the product term. Rearranging this we have
\begin{aligned}
g'(x) &= -2\frac{1 - x^2}{\sqrt{1-x^2}} \\
& = -2 \sqrt{1 - x^2}.
\end{aligned}
And so we have
\begin{aligned}
A'(z) &= Rg'(z/R) \\
& = -2R \sqrt{1 - (z/R)^2} \\
& = -2 \sqrt{R^2 - z^2}.
\end{aligned}
Substituting this into the original formula provided for $f_Z(z)$ gives the desired answer.


Q:

Getting "Error: ConnectFailure (Connection refused)" when running safaridriver using Safari Technology Preview

Due to the issue in detecting element visibility in the current version of Safari and safaridriver, as mentioned here, I attempted to launch our tests using Safari Technology Preview. The call is here:
return new SafariDriver("/Applications/Safari Technology Preview.app/Contents/MacOS/");

This seems to work, as it launches Safari Technology Preview when the test begins. However, after it is launched, nothing happens and I receive the following:
Error: ConnectFailure (Connection refused)

The full stacktrace is here:
1) Error : TESTNAME
OpenQA.Selenium.WebDriverException : A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URL http://localhost:62221/session. The status of the exception was ReceiveFailure, and the message was: Error getting response stream (ReadDone2): ReceiveFailure
  ----> System.Net.WebException : Error getting response stream (ReadDone2): ReceiveFailure
  ----> System.Exception :   at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00000] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0
  at System.Net.WebConnection.ReadDone (System.IAsyncResult result) [0x00000] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0
  at System.Net.Sockets.SocketAsyncResult+<Complete>c__AnonStorey0.<>m__0 (System.Object _) [0x00000] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0
  at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0
TearDown : System.NullReferenceException : Object reference not set to an instance of an object
  at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse (System.Net.WebRequest request) [0x000ce] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute (OpenQA.Selenium.Remote.Command commandToExecute) [0x000bd] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute (OpenQA.Selenium.Remote.Command commandToExecute) [0x00038] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Remote.RemoteWebDriver.Execute (System.String driverCommandToExecute, System.Collections.Generic.Dictionary`2[TKey,TValue] parameters) [0x00014] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession (OpenQA.Selenium.ICapabilities desiredCapabilities) [0x0001e] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Remote.RemoteWebDriver..ctor (OpenQA.Selenium.Remote.ICommandExecutor commandExecutor, OpenQA.Selenium.ICapabilities desiredCapabilities) [0x0001e] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Safari.SafariDriver..ctor (OpenQA.Selenium.Safari.SafariDriverService service, OpenQA.Selenium.Safari.SafariOptions options, System.TimeSpan commandTimeout) [0x0000e] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Safari.SafariDriver..ctor (System.String safariDriverDirectory, OpenQA.Selenium.Safari.SafariOptions options, System.TimeSpan commandTimeout) [0x00007] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Safari.SafariDriver..ctor (System.String safariDriverDirectory, OpenQA.Selenium.Safari.SafariOptions options) [0x00000] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at OpenQA.Selenium.Safari.SafariDriver..ctor (System.String safariDriverDirectory) [0x00007] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
  at Core.Selenium.SafariDriverFactory.CreateDriver (Core.Selenium.BrowserProfileManager profileManager) [0x00001] in <a2c49999051b4e8fb6c51d2ee4bca4b5>:0
  at Core.Selenium.DriverController.CreateWebDriver (Core.Enums.DriverType type) [0x00078] in <a2c49999051b4e8fb6c51d2ee4bca4b5>:0
  at Core.Selenium.DriverController..ctor (Core.Enums.DriverType type, System.DateTime creationTime, System.Boolean useProfile) [0x00045] in <a2c49999051b4e8fb6c51d2ee4bca4b5>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8f2c484307284b51944a1a13a14c0266>:0
--WebException
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00064] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0
  at System.Net.HttpWebRequest.GetResponse () [0x0000e] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0
  at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse (System.Net.WebRequest request) [0x00008] in <1d3f371c7d3240a69d2057d5d4e507e9>:0
--Exception
  at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00044] in <5071a6e4a4564e19a2eda0f53e42f9bd>:0

NOTE: I do not get this error if I use the current release version of Safari.
I have implemented code in dotnet using Selenium 3.0.1.  I am using Safari Technology Preview v. 22, macOS Sierra 10.12.3.  Allow Remote Automation is checked in the Develop menu. I have ran /Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver once manually.
Any ideas on how to get this working?

A:

In Python, here is what I did:
driver = webdriver.Safari(port=0, executable_path="/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver")
driver.get("https://www.google.com")

You may also want to look at:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/safari/SafariOptions.html
And here: https://github.com/SeleniumHQ/selenium/issues/3506
where lmtierney said:

That would depend on the language bindings you're using. You should be able to pass the executable path somewhere and it would be /Applications/Safari Technology Preview/Contents/MacOS/safaridriver. Some language bindings allow a flag to automatically use the tech preview safaridriver.

I hope this is helpful. :)


Q:

episode and # -- can the two be used together?

For example, on the Internet, there's a podcast for ESL learners called Culips (they are based in Montreal, Canada). They have two kinds of podcasts there—one is called Catchword and the other one Chatterbox. When they begin their podcasts, they usually say something like this, "Hello, English learners and we're back with another Chatterbox episode for you." I've recently started downloading their podcasts and now I want to give the files that I've downloaded proper titles (in so-called MP3 tags). I was just wondering what would be the right way (grammatically, semantically or whatever) to name a particular episode of the podcast. For instance:

Catchword Episode 156: Movers and Shakers

Does that sound alright to you? Or maybe this one is better (with the pound sign):

Catchword Episode #156: Movers and Shakers

And how would you say that now? "catchword episode number one hundred fifty-six"?
Please feel free to chime in with your suggestions.

A:

Either way is fine.  The concept of a podcast "episode number" is similar to the concept of a magazine "issue number".  Similarly, the concept of a podcast "season number" is similar to the concept of a magazine "volume number".
Abbreviation or Omission of "Number":
Including "Number" (abbreviated to "#") is more formal.  The "#" abbreviation is about as informal as omitting "Number".  It is OK to omit the "Number" (or "#"), because the episode number (such as "156") is obviously a number. Some computerized databases have trouble storing (or displaying) the "#" sign.
Other abbreviations for "Number" are "num." and "no."  I recommend avoiding the "no." abbreviation, because it is easy to confuse it with the English word "no".
Pronunciation:
"Catchword Episode 156" could be pronounced as either "Catchword Episode one fifty-six" or "Catchword Episode number one fifty-six".
"Catchword Episode #156" would be pronounced as "Catchword Episode number one fifty-six".
If the reader is being very formal, the reader would say "one hundred fifty-six" instead of "one fifty-six".


Q:

Apache2 no longer working in Yosemite

After upgrading OSX to yosemite, my local apache2 server is no longer working.  Running
sudo apachectl restart

does not give any error, however nothing is running on localhost:80, and nothing is written to the log files in /var/log/apache2/ either. The log files have not been touched after the upgrade of OSX. However, system.log shows:
Oct 29 13:27:45 Jeroens-MBP sudo[1210]:   jeroen : TTY=ttys000 ; PWD=/private/var/log/apache2 ; USER=root ; COMMAND=/usr/sbin/apachectl start
Oct 29 13:27:45 Jeroens-MBP com.apple.xpc.launchd[1] (org.apache.httpd): Please switch away from OnDemand to KeepAlive.
Oct 29 13:27:45 Jeroens-MBP com.apple.xpc.launchd[1] (org.apache.httpd[1213]): Service exited with abnormal code: 1

In addition, my /usr/include dir seems completely empty after the upgrade, not sure if that is related.

A:

Okay I solved my problem. It seems like the upgrade of apache had disabled mod_ssl. To debug apache2 config files in osx, run apachectl without any parameters:
Jeroens-MBP: jeroen$ sudo apachectl
AH00526: Syntax error on line 10 of /private/etc/apache2/other/mobilize.conf:
Invalid command 'SSLProxyEngine', perhaps misspelled or defined by a module not included in the server configuration


Q:

Receiver 'ClassName' is a forward class and corresponding @interface may not exist

Im currently trying to find a UIPickerTable within the UIPickerView.subviews ... so i loop through and do isKindOfClass:[UIPickerTable class] .... which works.. but because the header of UIPickerTable isn't exposed i get a warning that "receiver 'UIPickerTable' is a forward class and corresponding @interface may not exist'
In order to even be able to compile I do @class UIPickerTable, and obviously it want's me to #include it.
I'm wondering if there's a way to get around seeing this warning.
TIA!

A:

Maybe you have @class UIPickerTable in your .h file and you did not have #import UIPickerTable.h on your {RootViewController}.m file

A:

I don't think that you can suppress that warning with a compiler option. You could make it go away by simply creating your own header file for the class, containing:
@interface FacesViewController : NSObject {
}

I suppose it goes without saying that having your application depend on the internal structure of a UIKit class is probably not the best strategy. Presumably you have a good reason for mucking about inside the UIPicker...


Q:

How to convert timestamp string to timestamp in another timezone

I have a string of a timestamp in UTC
val x = "2018-09-26T15:05:19.1121042Z"

I would like to have a function like this to convert it to a timestamp object in CST timezone.
def StringToTimeStamp(str: String): Timestamp = {
  val timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  val timeZone = TimeZone.getTimeZone("America/Chicago")
  timeFormat.setTimeZone(timeZone);
  val now = timeFormat.format(str)
  val ts = java.sql.Timestamp.valueOf(now)
  ts
}

However, I do not know the SimpleDateFormat format for my string, as I can't put in letters like T / Z as they appear in my string x.  How would I accomplish this?

A:

Zulu time
The Z on the end of your input string means UTC, and is pronounced “Zulu”.
ISO 8601
Your input string is in standard ISO 8601 format. The java.time classes use these standard formats by default when parsing or generating strings.
Instant
Parse your string as an Instant. Instant represents a moment in UTC with a resolution of nanoseconds.
Instant instant = Instant.parse("2018-09-26T15:05:19.1121042Z") ;

Your JDBC driver may be able to take that Instant.
myPreparedStatement.setObject( … , instant ) ;

OffsetDateTime
If not, your JDBC 4.2 or later driver is required to accept OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;

Avoid java.sql.Timestamp
If you have on older JDBC driver before JDBC 4.2, then fall back to using the terrible java.sql.Timestamp. But use these legacy date-time classes only if you absolutely must, as they are an awful mess.
You can convert between the modern and legacy classes by calling new conversion methods added to the old classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

…and…
Instant instant = ts.toInstant() ;

Time zone
Presumably you were asking about java.sql.Timestamp because you are exchanging the value with a database.
Your time zone of Chicago is irrelevant to database work, as most databases store a moment in UTC.
ZonedDateTime
But for presentation to the user, you may want to adjust from UTC to a time zone.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Generate a string in localized format
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.US ) ;
String output = zdt.format( f ) ;


Q:

ADODB COM Object returns -1 for bit values of 1

I am busy experimenting with ADODB as a means to write prepared scripts on customers' databases as it is infinitely better than batch scripting with sqlcmd.
Early on I noticed that sometimes ADODB results would differ from the results given by osql or sqlcmd and on further investigation I found that it always seemed to be in columns that hold a boolean value. If I run the following code I get -1:
declare @test bit
set @test=1
select top 1 @test

When logically it should return 1 as according to the MSDN and w3schools documentation the bit data type on SQL server holds either a 1, 0 or null.
Could anyone explain what is causing this and how to prevent it?
Will exporting information from my database and then importing the -1 rather than a 1 cause issues if the importing is also done with ADODB?

A:

Demonstration Code
ConnectionString = "Provider=SQLNCLI11;"
ConnectionString = ConnectionString & "Server=localhost;"
ConnectionString = ConnectionString & "Database=master;"
ConnectionString = ConnectionString & "Trusted_Connection=yes;"

Dim Conn As Object
Set Conn = CreateObject("ADODB.Connection")
Conn.Open ConnectionString
Set Recordset = Conn.Execute("SELECT convert(bit, 1) as bit")

MsgBox Recordset.Fields("bit").Type, 0, "FieldType"
MsgBox VarType(Recordset.Fields("bit").Value),0,"VarType"

This shows that the SQL Server data type bit maps to 11 which is the enumerated values ADODB.DataTypeEnum.adBoolean
https://msdn.microsoft.com/en-us/library/ms675318(v=vs.85).aspx
Which in turn corresponds to a varian of Vartype 11 (VariantType.vbBoolean) https://msdn.microsoft.com/en-us/library/32bbtt2s(v=vs.90).aspx
So the bit Values 0 and 1 aren't getting directly translated to the numbers 0 and -1 by ADODB.
They're actually getting translated to False & True which in turn correspond to the integers 0 and -1 when you implicitly convert them to integers.
You can demonstrate this by issuing the following commands in the immediate window.
Debug.Print CInt(False)
Debug.Print CInt(True)

Quite where this leaves you in terms of practical advice I'm not sure but you should probably be treating these values as boolean variables in your code as opposed to numbers.
Luckily SQL Server will implictly convert -1 back to 1 on the database side so you don't need to worry about that
 DECLARE @table table (b bit)
 INSERT @table  (b) VALUES(-1)
 SELECT b from @table

Gives you
(1 row(s) affected)
b
-----
1

(1 row(s) affected)

Hopefully this resolved more confusion than it caused


Q:

Using Mixins in flutter

I am not able to use mixins in my flutter app, It says:

The class 'UserModel' can't be used as a mixin because it extends a class other than Object

A:

It wasn't officially possible to have mixins with that extends something for a long time.
It has been recently enabled, but with another syntax:
mixin UserModel on Model {
  // do some stuff
}


Q:

Why don't we hard-prevent users from nominating themselves as a moderator candidate if they were suspended in the past year?

I know that users aren't permitted to nominate themselves as moderator candidates if they were suspended after one year. Additionally, such users are shown a message before posting their nomination.
I know that this is technically feasible (i.e. that suspensions across the network are accessible by other sites), given that message, but why was the decision made to simply provide a soft block, allowing users to dismiss that prompt and nominate themselves anyway? Why not outright prevent them from nominating themselves (i.e. remove the "I want to continue" link in that prompt)?
I understand that users suspended within the past year can nominate themselves if they contact the SE team and obtain permission, and it should be easy for employees to clear the past suspension from their record, which would allow them to run, or otherwise set some flag allowing them to run on a certain site.
Please note that this is a neutral question; I'm simply asking why the decision was made to implement it that way.

A:

Because that's actually more work.
So far as I've observed, nominations from folks with suspensions in recent memory are doing their respective nominees no favors; they inevitably end with the past being dredged up, the candidate's name being dragged through the mud, and everyone feeling just a bit less happy about the whole experience.
So while the prohibition on nominations from recently-suspended users is primarily intended to benefit the larger community, it is in everyone's best interest if it is respected.
Thus, the lack of a hard block leaves two possibilities:

Folks whose suspensions were of no consequence, in error, or "for science" (active moderators suspending themselves) and thus would invariably be allowed.
Folks who lack the situational awareness to recognize the futility of their efforts, and would attempt to bash their heads against such a wall anyway.

For the former, a hard block just creates busywork for us and an annoyance for the nominee.
For the latter, a hard block leaves only the option of making a spectacle of themselves. This is not something we'd like to see, no matter who is involved. Much kinder to quietly remove their nomination and privately message them.


Q:

Getting all the words of a string in to an array?

I have a string as follows:
is newegg.com a scam ? – fraudwatchers
When I put that string in to an array, using the following code:
$title_word = str_word_count(“is newegg.com a scam ? – fraudwatchers”, 1);

It gives me the following results:
  0 => string 'is' (length=2)
  1 => string 'newegg' (length=6)
  2 => string 'com' (length=3)
  3 => string 'a' (length=1)
  4 => string 'scam' (length=4)
  5 => string '-' (length=1)
  6 => string 'fraudwatchers' (length=13)

I would like one array element to contain the whole world “newegg.com” and another array element to contain “?” Can you please tell me how I can do this with an example. Any help would be greatly appreciated.

Updated:
if I use explode(' ', $my_text); This does not work correctly. if I were to go through a body of a web page, it assign few words to one array element with new lines.
(I need none words in my array as well).

A:

As far as I understand your problem, you can try following:
$sentence = 'is newegg.com a scam ? - fraudwatchers';
$words = explode(' ', $sentence);

A little more advanced answer - this one will handle all white characters such as tabs and newlines:
$words = preg_split("/\s+/", $sentence);

If you need to filter out non-words, you can also use array_filter. Note that this won't handle non-latin words.
$words = array_filter($words, function($word) { return preg_match('/^\w+$/', $word); });

For multilingual word matching, you can check Unicode character properties article.


Q:

Python - Disable nested for loop according to boolean value

What is the best way to rewrite nested for-loops like this:
for i in my_generator_function(args...):
    #do stuff...

    for j in another_generator_function(args...):
        #do more stuff

if i want to disable the first for-loop, according to a boolan value, but always keep the inner one? Of course I could use an if/else around it, and put a duplicate of the inner loop in the else block. but is there a better way?

A:

If I understood correctly you want to loop 100 or 0 times through something and keep the inner 10.
If that is what you want, try this:
my_value = False

checker = lambda x, y: y if x else range(1)

def somefunc():
    return range(100)

for i in checker(my_value, somefunc()):
    if my_value:
        #do stuff
    for j in range(10):
        #do stuff


Q:

How much money does it cost to play FIFA 12 online?

How much money does it cost to play the PC version of FIFA 12 online?
Not regarding Internet or energy costs but only the connection to the server.

A:

Playing Fifa12 on the PC is free. Unlike for example the Xbox 360 where a subscription to XBox live is needed, the PC version only requires an active internet connection and an original copy of the game.
So if you exclude costs for your connection, power and the original cost of the game online play is free.


Q:

What's the standard way to create custom conversion between types in Rust?

If I defined some enum and wanted to create a parser from string to that type, is there something better than just:
impl TheType {
    fn from_str(s: &str) -> TheType {
        // ...
    }
}

A:

The right way for converting from a string / parsing text is to implement the FromStr trait. For the example from the question it would look like this:
use std::str::FromStr;

enum Failure {
    ReasonOne,
    ReasonTwo,
}

impl FromStr for TheType {
    type Err = Failure;

    fn from_str(s: &str) -> Result<TheType, Self::Err> {
        unimplemented!()
    }
}


Q:

What constitutes "wrongful" hesitation in bridge?

The protagonist is West (W). Declarer leads a small card of a suit in which dummy, to W's left, has A8. West hesitates before playing in the following four situations:

He has Kx (x<8). This is the mark of weak player who has "given away the game," and the declarer has all the advantages.
He has T6, which "straddle" the 8. If the tournament director (TD) asks why he hesitated,  he responds that he was trying to decide whether or not to "top" the 8.
He has T9 or 76, "equal" holdings that lose to the A, but either beat, or fail to, the 8. If the TD asks him for an explanation of his conduct, he replies that he was trying to decide whether or not falsecard the higher card to induce the declarer to lose count.
He has a singleton, and hence no decision to make, and should play "naturally." As it is, he's pretending that he has more than one card when he doesn't.

The last case would clearly be one of wrongful hesitation. Would any of the other three cases, or others that I missed, constitute such misconduct, and why?

A:

I believe that cases 1-3 are all ethical, but these are simple problems that should have been solved at the end of some earlier trick (In duplicate bridge, after all the cards to a trick have been faced, players should indicate that they are thinking about the hand by keeping their card face up. Play does not proceed until all players have turned their cards face down.).
None of 1-3 damage declarer, and in any case you may pause to think whenever you have an actual bridge problem. However, your hesitations may also transmit unauthorized information to your partner, and so your partner may be constrained in their future actions.
Jeff Goldsmith has a useful and interesting discussion about unauthorized information on his website, which covers this area, and discusses what you should do in case partner has accidentally given you unauthorized information.

A:

Hesitating in case 3 is clearly unethical, as West has no problem in playing from either T9 or 67 in this scenario. One may hesitate in order to determine which card to play from a technical perspective, but not whether or not to signal to partner without an accompanying technical problem. Otherwise one would always hesitate when showing an even number with 2, and never hesitate when showing an even number with 4, thus creating a(n illegal) signal that clearly distinguished between holdings of 2 and 4 cards based on the manner in which the cards were played rather than the particular cards played.
Even in the absence of the above, hesitating would clearly be seen as an attempt to mislead declarer on the location of a single card between the A and 8. It is quite likely that Declarer is not harmed in this instance, but that does not preclude the award of an adjusted score against the offending side, EW here. The appropriate penalty for a first offense would be the actual score for NS, and lower of actual and Average-minus for EW.
Update - Added comments from below

1) "False carding to make the declarer lose count" is not illegal in this instance, but "reinforcing" it by hesitating is, right? –  Tom Au
Yes; but it is important to realize that all signals not made in tempo comprise Unauthorized Information (UI) for partner; namely that there was a question about whether or not to make the signal, and thus that the signal is in some fashion weak. Likewise false carding must be done in tempo in order to not be seen as an attempt to improperly deceive declarer; but this is really just a special case of the preceding as partner is also given UI.
2) In example 2 (and even example 1), you have two cards that "straddle" the 8, so you have a technical problem, right? Then hesitating under those circumstances would be amateurish, but not wrongful, right? -- Tom Au
Yes, that is correct; however the decision on carding if Declarer plays low towards Dummy should have been made as part of West's review of dummy right after it came down. Hesitating when the play occurs is still UI for partner, and will hinder effective defense in consequence. Practice taking a full 3/4 second or so on every play as defender, to give yourself a couple tenths reaction/thinking time when you need it.
Yes, the experts do what you suggested, and it's the amateurs that wait until it's too late = Tom Au
So true.


Q:

Using libmms from Objective-C

I want to use libmms in an objective-c project. I've taken the project from here - http://www.tunein-radio.com/lgpl.html - and included the libmms library in my own project. This avoids me having to compile libmms myself. Initially I just want to see if it works and hopefully output some audio.
Here's what I have so far in my header file:
#import <UIKit/UIKit.h>
#import "mmsio.h"
#import "mms.h"

#define streamURL @"path/to/stream"

@interface radiotestAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
 struct mms_t_io *io;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

I'm not really sure where to go from here but think I need to use this method from mms.h:
mms_t* mms_connect (mms_io_t *io, void *data, const char *url, int bandwidth);

However, I'm not well versed enough in C to unravel the libmms code. Can anyone offer any advice? I'd be happy to pay for some tuition but want to understand this myself.
What frameworks should I be using to read the mms_t response type from the above method?
Thanks,

A:

I never used libmms but when looking into the source code the interface seems to be very simple:

You connect with mms_connect and receive a connection instance.
You read from the stream using the opened connection using mms_read.
You close the connection using mms_close.

For advanced functionality you have the other mms_* functions.
The IO (mms_io_t) can be null. In this case a default implementation will be used for I/O.
BTW I wonder how you would program in Objective-C without being versed enough to understand C code (the libmms code seems straight forward and easy to understand).
Update:
I cannot see where the libmms does any video decoding. There are some methods for seeking and getting header/packet information. I don't have any knowledge about video decoding - so I cannot say if you have to decode the stream data prior to playing it or if the iPhone can handle it directly.


Q:

What is /run/user/1000/gvfs/

I connected my action camera (GoPro Hero 5) to the computer running Ubuntu 16.10 LTS to download files. To my surprise, I did not see the camera's folder in /media/. Running find | grep DCIM from the root folder discovered a folder with the following path, which contained the video files I was looking for:
/run/user/1000/gvfs/gphoto2:host=%5Busb%3A003%2C094%5D/DCIM/

So, what is /run/user/1000/gvfs/ and how is its purpose different than /media/?

A:

All roads lead to Gnome
Ubuntu is based upon many things plus home grown programming from Canonical (the owners of Ubuntu). Most people know it is based on Linux kernel and provides a "GNOME" Desktop environment. But it is also based on Debian and perhaps just as important Gnome Internals. It is so intrinsic I dare to say in Ubuntu that: "All roads lead to Gnome".
What is GIO / gvfs?
In your question /run/user/1000/gvfs/ the gvfs component stands for "Gnome Virtual File System". Your camera and Android phones are mounted in this "User Space" outside of "Kernel Space" where a normal "mount" occurs.
To learn more about GIO (Gnome Input Output I surmise) see here and here. Ubuntu has a page about using GIO to mount devices using the gvfs-mount command.
The other component in your question /run/user/1000/gvfs/ is the /run/user component. This was created by systemd to circumvent using the /tmp directory which was common practice for such devices because it side-stepped network "rules". See here.
The other part of your question is how is it different from /media?
The /media directory is where removable storage is located. The removable storage is in a familiar file format such as ext4, fat or ntfs. The device names and mount names are static.
Your Android phone is not just removable storage but a removable foreign operating system that has storage. The storage is generally accessed with MTP. However, there is a host of programs to communicate with the phone. That is why it goes into /run/user/1000/gvfs. Samba also goes into the same directory chain but I haven't researched that one yet.
In the /run/user/1000 directory structure the mount names are dynamic and change with every connection. For example my phone currently is:
$ ll /run/user/1000/gvfs/mtp:host=%5Busb%3A001%2C013%5D
total 0
dr-x------ 1 rick rick 0 Dec 31  1969 ./
dr-x------ 3 rick rick 0 May  9 18:20 ../
drwx------ 1 rick rick 0 Dec 31  1969 Internal storage/
drwx------ 1 rick rick 0 Dec 31  1969 SD card/

The USB enumeration is notorious for changing so you can be assured the directory name will be different next time. /media "stuff" on the other hand is static.
Notice the dates shown by Ubuntu 16.04 under Kernel 4.14.34. I haven't had this Android Smartphone since the year 1969. I guess we can call this a bug.


Q:

Is my proof, by strong induction, of for all $n\in\mathbb{N}$, $G_n=3^n-2^n$ correct?

Let the sequence  $G_0, G _1, G_2, ...$ be defined recursively as follows:
$G_0=0, G_1=1,$ and $G_n=5G_{n-1}-6G_{n-2}$ for every $n\in\mathbb{N}, n\ge2$.
Prove that for all $n\in\mathbb{N}$, $G_n=3^n-2^n$.

Proof. By strong induction. Let the induction hypothesis, $P(n)$, be $G_n=3^n-2^n$
Base Case: For $(n=0)$, $P(0)$ is true because $3^0-2^0 =0$
For $(n=1)$, $P(1)$ is true because $3^1-2^1=1$
Inductive Step: Assume that $P(n-1)$ and $P(n-2)$, where $n\ge2$, are true for purposes of induction.
So, we assume that $G_{n-1}=3^{n-1}-2^{n-1}$ and $G_{n-2}=3^{n-2}-2^{n-2}$, and we must show that $G_{ n }=3^{ n }-2^{ n }$.
Since we assumed $P(n-1)$ and $P(n-2)$, we can rewrite $G_n=5G_{n-1}-6G_{n-2}$ as $G_n=5(3^{n-1}-2^{n-1})-{ 6 }(3^{n-2}-2^{n-2})$
So, we get:
$\Rightarrow G_n=5\cdot 3^{ n-1 }-5\cdot 2^{ n-1 }-(\frac { 6 }{ 3 } \cdot 3^{ n-1 }-\frac { 6 }{ 2 } \cdot 2^{ n-1 })$
$\Rightarrow G_n=5\cdot 3^{ n-1 }-5\cdot 2^{ n-1 }-2\cdot 3^{ n-1 }+3\cdot 2^{ n-1 }$
$\Rightarrow G_n=5\cdot 3^{ n-1 }-2\cdot 3^{ n-1 }-5\cdot 2^{ n-1 }+3\cdot 2^{ n-1}$
$\Rightarrow G_n=3\cdot 3^{ n-1 }-2\cdot 2^{ n-1 }$
$\Rightarrow G_n=\frac { 1 }{ 3 } \cdot 3\cdot 3^n-\frac { 1 }{ 2 } \cdot 2\cdot 2^n$
$\Rightarrow G_n=3^n-2^n$

The only real issue I have at this point is that I don't know how to properly conclude this proof with a final statement. A hint/guidance in that regard would be much appreciated.
In addition, please feel free to offer advice and/or constructive criticism about my proof.

A:

You have the right idea, but there are some minor points that need correction.
The strong induction principle in your notes is stated as follows:
Principle of Strong Induction $\ $ Let $\,P(n)\,$ be a predicate. If

$\ P(0)$ is true, and
for all $\,n\in \Bbb N,\ P(0), P(1),\ldots, P(n)\,$ together imply $\,P(n\!+\!1)\,$ then $\,P(n)\,$ is true for all $\,n\in\Bbb N$

Your $\,P(n)\,$ is $\, G_n = 3^n - 2^n.\,$  You have verified that $\,P(0)\,$ is true.
Your induction hypothesis is that $\,P(k)\,$ is true for all $k \le n.\,$ You have essentially shown that $\,P(n\!-\!1),P(n)\,\Rightarrow\,P(n\!+\!1)\,$ but that only works for $\,n\ge 1$ (else $\,P(n-1)\,$ is undefined). Thus you need to separately verify $\,P(1)\,$ (to be pedantic, this is part of the inductive step, not the base case, according to the above formulation of strong induction, though that is a somewhat arbitrary distinction)
It is illuminating to observe that the recurrence in the induction is a special case of
$$ a^{n+1}-b^{n+1} =\, (a+b)(a^n-b^n) -ab (a^{n-1} - b^{n-1})$$
which can be verified directly or derived from the fact that $\,a,b\,$ are roots of
$$(x\!-\!a)(x\!-\!b) = x^2\! - (a\!+\!b) x + ab\,\Rightarrow\, x^{n+1}\! = (a\!+\!b)\,x^n - ab\, x^{n-1}$$
The proof will be simpler (and more insightful) if you work with this general case, i.e. prove that $\,f_n = a^n - b^n\,$ satisfies $\,f_{n+1} = (a+b) f_{n} - ab f_{n-1},\ f_0 = 1,\ f_1 = a-b\,$ for all $\,n\ge 0.\,$ Then your problem is just the special case $\,a,b = 3,2,\,$ and the inductive step is much clearer.


Q:

Call the hardware back button programmatically?

I know that one can overwrite the Back Button functionality in Android, but I was wondering if there was a method or anything I could call that would functionally do the same thing as pressing the hardware button.

A:

You can send the back button press to the system like this
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));

Or you can override the back button press and call
finish();

on your Activity. That basically does the same thing as the generic back button.

A:

Just call this.onBackPressed(); in Activity.

A:

If you want just "press" hardware button,
create service extended from AccessibilityService:
class ExampleAccessService:AccessibilityService() {
    override fun onInterrupt() {
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
    }

    fun doAction(){
        performGlobalAction(GLOBAL_ACTION_RECENTS)
//        performGlobalAction(GLOBAL_ACTION_BACK)
//        performGlobalAction(GLOBAL_ACTION_HOME)
//        performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
//        performGlobalAction(GLOBAL_ACTION_POWER_DIALOG)
//        performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
//        performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
    }
}

Call doAction() where you want action
Add to Manifest:
<application
...
    <service
        android:name=".ExampleAccessService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="Name of servise" // it will be viewed in Settings->Accessibility->Services
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService"/>
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibility_service_config"/>
    </service>
...
</application>

accessibility_service_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackAllMask"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="false"
    android:description="your description"
    android:notificationTimeout="100"
    android:packageNames="your app package, ex: ex: com.example.android"
    android:settingsActivity="your settings activity ex: com.example.android.MainActivity" />

for more info look at https://developer.android.com/guide/topics/ui/accessibility/services.html


Q:

gridview custom adapter search

i have grid view , and custom adapter i want to search the items that are in the grid view by a search view ,,,
the thing is i don't know how to implement a search view along with a custom adopter ,, because i have a click event in the custom adapter which is when the user clicks an item it downloads a pdf file form internet ,, how can i add search view that will search the grid view items in with the custom adapter click even running ,
i am new usually i copy and paste the code i am 30% new .
this is my main activity

package com.alhaddadsoft.ammar.gridview;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    GridView gv;
    GridView gv1;
    TextView newtext;
    Context context;
    ArrayList prgmName;
    public static String [] prgmNameList={"احمد عبده ماهر","احمد داوود","احمد صبحي منصور","لكشف الموروث اقرأ هذا أولا","الختان للذكور والاناث","الصادق النيهوم","الطريق إلى بيت المقدس","اوشو","بن فرناس","جمال البنا","جورج طرابيشي","زكريا اوزون", "سلامه موسى","سلسلة عندما نَطَقَ السراة","عبد الرزاق جبران","عبد الله القصيمي","علي الوردي","علي شريعتي","فاضل الربيعي","فرج فوده","كمال الصليبي","محمد اركون","محمد شحرور","محمد علي المحمود","محمود ابو ريه","نيازي عز الدين","هشام جعيط"
        ,"أبو الأعلى المودودي - الخلافة والملك","أسوار الصمت قراءة في الحقوق المدنية في السعودية لـ د. وليد الماجد","احمد امين - فجر الاسلام","اعمدة الحكمة السبعة . لورنس العرب","الارهابى ",
            " الاسلام واصول الحكم -- على عبد الرازق","الاسلام وجراب الحاوي . شاكر النابلسي","الاضافة النوعية القرانية.مصطفى بوهندي",
            "التأثير المسيحي في تفسير القران","التوراة اليهودية مكشوفة على حقيقتها","الخلافه الاسلاميه.محمد سعيد عشماوي","الدولة الاسلامية ،الجذور والتوحش عبدالباري عطوان","الدين واحتكار الحقيقه.واثق غازي","السادس من نوفمبر قيادة المراة للسيارة","السلطة في الاسلام لعبدالجواد حسين","السلفيون ايضا يدخلون النار.وليد طوغان","السنة بين الاصول والتاريخ ذويب رسالة دكتوراة","العقل الايماني","القران وثالوث الاستبداد.نشأت جعفر",
            "القران ولغة السريان. احمد علي الجمل","اللاهوت العربى-يوسف زيدان","المؤمن الصادق - إيريك هوفر","الملوك المحتسبون حجم صغير","امي كاملة عقل ودين","انتكاسة المسلمين الى الوثنية - سيد القمني","بالداخل . اشرف فياض","بالداخل . اشرف فياض","تاريخ نجد . بن غنام مؤرخ محمد بن عبدالوهاب","تحرير المرأه من عهد الرساله","تزييف الاسلام.انور اسحاق","جغرافية التوراة _زياد منى","حتى لا يعود جهيمان . توما ... غهامر . ستيفان لاكروا",
            "حكاية التدين السعودي . وحيد الغامدي","حواء والخطيئة","حوار حول القران وحده . محمد توفيق صدقي","رجم الزاني","طبائع الإستبداد ومصارع الإستعباد","عبد الرزاق عيد .. سدنة هياكل الوهم , نقد العقل الفقهي","عبيد بلا اغلال.تاريخ جزيرة العرب القريب","فتنة القول بتعليم البنات.عبدالله الوشمي","قدماء المصريين اول الموحدين","كارثة فلسطين . عبدالله التل","لعبة الامم","ما بعد الشيوخ ، انهيار ممالك الخليج","مابعد الصحوة.عبدالله الغذامي","مشكلة الحديث","معجزة اختيار اللفظ في القرآن",
            "مقالة العبودية الطوعية","من يجرؤ على الكلام .بول فندلي","نقد الخطاب الديني لنصر ابو زيد","نقد الخطاب السلفي ابن تيمية نموذجا.رائد السمهوري","ورثة محمد .جذور الخلاف السني الشيعي"

    };
    public static int [] prgmImages={R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon
    ,R.drawable.book1,R.drawable.book2,R.drawable.book3,R.drawable.book4,R.drawable.book5,R.drawable.book6,R.drawable.book7,R.drawable.book8,R.drawable.book9,R.drawable.book10,R.drawable.book11,R.drawable.book12,R.drawable.book13,R.drawable.book14,R.drawable.book15,R.drawable.book16,R.drawable.book17,R.drawable.book18,R.drawable.book19,R.drawable.book20,R.drawable.book21_,R.drawable.book21,R.drawable.book22,R.drawable.book23,R.drawable.book24,R.drawable.book25,R.drawable.book26,R.drawable.book27,R.drawable.book28,R.drawable.book29,R.drawable.book30,R.drawable.book31,R.drawable.book32,R.drawable.book33,R.drawable.book34,R.drawable.book35,R.drawable.book36_,R.drawable.book36,R.drawable.book37,R.drawable.book38,R.drawable.book39,R.drawable.book40,R.drawable.book41,R.drawable.book42,R.drawable.book43,R.drawable.book44,R.drawable.book45,R.drawable.book46,R.drawable.book47,R.drawable.book48,R.drawable.book49,R.drawable.book50,

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gv=(GridView) findViewById(R.id.gridView1);
        gv.setAdapter(new CustomAdapter(this, prgmNameList, prgmImages));

    }
    public void openactivity1(){
        edittext();
        //Intent i = new Intent(this, AhmedDaod.class);
       // startActivity(i);

}
public void edittext(){
  //  newtext =  (TextView)findViewById(R.id.textView5);
   // newtext.setText("hello");
}
}

This is my CustomAdapter acteivity

package com.alhaddadsoft.ammar.gridview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CustomAdapter extends BaseAdapter {

    String[] result;
    Context context;

    int[] imageId;
    private static LayoutInflater inflater = null;

    String dwnload_file_path;
    String file_name;
    String imageViewD;
    String textViewD;

    GridView gridview;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages ) {
        // TODO Auto-generated constructor stub
        result = prgmNameList;
        context = mainActivity;
        imageId = prgmImages;
        inflater = (LayoutInflater) context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder {
        TextView tv;
        ImageView img;
        TextView edit ;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final Holder holder = new Holder();
        View rowView;

        rowView = inflater.inflate(R.layout.programlist, null);
        holder.tv = (TextView) rowView.findViewById(R.id.textView1);
        holder.img = (ImageView) rowView.findViewById(R.id.imageView1);

        holder.tv.setText(result[position]);
        holder.img.setImageResource(imageId[position]);
        rowView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               // Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
                // String displayedText = ((TextView)((LinearLayout)myToast.getView()).getChildAt(0)).getText().toString();
                try {
                    if (result[position].equals("أبو الأعلى المودودي - الخلافة والملك")) {

                        new AlertDialog.Builder(context)
                                .setTitle("تحميل الكتاب")
                                .setMessage("هل تريد تحميل الكتاب?")
                                .setPositiveButton("تحميل", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // continue with delete
                                        dwnload_file_path = "http://www.jouhinabooks.com/get_file.php?id=470";
                                        file_name = "book1.pdf";
                                        imageViewD = "book1";
                                        textViewD = result[position];
                                        Downloadmethode();

                                    }
                                })
                                .setNegativeButton("رجوع", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // do nothing
                                    }
                                })
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .show();

                        //Intent intent= new Intent(context, AhmedDaod.class);
                       // intent.putextra("your_extra","your_class_value");
                        //context.startActivity(intent);

                        //MainActivity openactivity = new MainActivity();
                       // openactivity.openactivity1();
                        //edittext.setText("hello");
                    }

                } catch (final Exception e) {
                    Toast.makeText(context, "error  ", Toast.LENGTH_LONG).show();
                }

            }

        });

        return rowView;

    }
    public void Downloadmethode(){
        Intent d = new Intent(context, DownloadBook.class);
        d.putExtra("dwnload_file_path", dwnload_file_path);
        d.putExtra("file_name", file_name);
        d.putExtra("imageViewD",imageViewD);
        d.putExtra("textViewD",textViewD);
        context.startActivity(d);
    }
}

A:

This is how I implemented the search feature. Create two Lists, the searchList and the backUpList.
backUpList = loadMyData();
searchList.addAll(backUpList);

Now you have two lists that contain the same data. And because the lists contain only references to the objects there is no extra memory being used. Then feed the searchList to the adapter instead of the actual list.
adapter = new CustomAdapter(searchList*/,...other inputs*/);
gridView.setAdapter(adapter);

And now when you want to search in your data you empty your search list and search in you back up list. If an object should be shown then add it in your search list. Then notify the adapter and your search results are shown.
searchList.clear();
searchList.addAll(backUpList);
for(CustomObject object:backUpList){
    if(meetsSearchCriteria(object)){
        searchList.add(object);
    }
}
adapter.notifyDataSetChanged();

And adjust the rest of your code to work with the searchList instead of the actual data list.
You must change your adapter to take an ArrayList of objects as input and not a table as your code shows. Tables do not support changes in their size after their creation.


Q:

Sorting values consisting of chars and numbers in an List>() or asp:ListView

I have an Tuple List and I'm filling this list with all directorys of an folder and bind it to an asp:ListView with this code:
List<string> directoryContent = new List<string>(Directory.GetFileSystemEntries(dirPath);
List<Tuple<string, string>> directoryList = new List<Tuple<string, string>>();

for (int i = 0; i < directoryContent.Count; i++)
{
    FileAttributes attr = File.GetAttributes(directoryContent[i]);
    if (attr.ToString().Equals("Directory"))
    {
        String str = directoryContent[i].Remove(0, dirPath.Length);
        string count = Directory.GetFiles(directoryContent[i], "*.*", SearchOption.AllDirectories).Length.ToString();
        directoryList.Add(new Tuple<string, string>(str, count));
    }
}

directoryListView.DataSource = directoryList;
directoryListView.DataBind();

For example the found directories are

12
566
10001
10
templates
files

What would be the best way to sort the List or the ListView in this way? Thank you in advance.
I need to sort the directory that they are sorted in this order:

files
templates
10
12
566
1001

A:

You can use Linq for that.
//test data
List<string> list = new List<string>()
{
    "12",
    "566",
    "10001",
    "10",
    "templates",
    "files"
};

int tempInt;

//filter the numbers from the list and sort
var listNumbers = list.Where(x => int.TryParse(x, out tempInt)).Select(y => Convert.ToInt32(y)).OrderBy(z => z);

//filter the strings from the list and sort
var listStrings = list.Where(x => !int.TryParse(x, out tempInt)).OrderBy(y => y);

//join the two lists again
var orderedList = listStrings.Concat(listNumbers.Select(y => y.ToString())).ToList();

Update for Tuple List
List<Tuple<string, string>> list = new List<Tuple<string, string>>()
{
    new Tuple<string, string>("12", "NA"),
    new Tuple<string, string>("566", "NA"),
    new Tuple<string, string>("10001", "NA"),
    new Tuple<string, string>("10", "NA"),
    new Tuple<string, string>("templates", "NA"),
    new Tuple<string, string>("files", "NA")
};

int tempInt;

//filter the numbers from the list and sort
var listNumbers = list.Where(x => int.TryParse(x.Item1, out tempInt)).Select(y => new Tuple<int, string>(Convert.ToInt32(y.Item1), y.Item2)).OrderBy(z => z.Item1);

//filter the strings from the list and sort
var listStrings = list.Where(x => !int.TryParse(x.Item1, out tempInt)).OrderBy(z => z.Item1);

//join the two lists again
var orderedList = listStrings.Concat(listNumbers.Select(y => new Tuple<string, string>(y.Item1.ToString(), y.Item2))).ToList();


Q:

Synchronizing threads in Java

I have two threads modifying the same object, lets say MyObject, and so have synchronized the object. But in one of the threads another object is modified and in so doing has to call MyObject.
I.e.
public void run(){
   synchronized(MyObject){
             ...
            anotherObject.modify();//<----calls MyObject
             ...
    }
 }

This is causing ConcurrentModificationExceptions. I don't know how to solve this. If I don't synchronize, I get exceptions as both threads try to call MyObject. How can I fix this?
UPDATE: The code is for the Android device. I didn't mention it before, because there are no Android specific objects in play here.
The LogCat output isn't very helpful

02-03 02:47:43.660: ERROR/AndroidRuntime(5258): Uncaught handler: thread main exiting due to uncaught exception
  02-03 02:47:43.670: ERROR/AndroidRuntime(5258): java.util.ConcurrentModificationException
  02-03 02:47:43.670: ERROR/AndroidRuntime(5258):     at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
  02-03 02:47:43.670: ERROR/AndroidRuntime(5258):     at com.jjg.myapp.gameunit.findEnemy(MoveableUnit.java:656)//<---in this method Gamestate's collections are iterated through
  02-03 02:47:43.670: ERROR/AndroidRuntime(5258):     at com.jjg.myapp.gameunit.update(GameUnit.java:416)

The Object that I was trying to synch is essentially a GameState called gs. It houses an assortment of ArrayLists, arrays and other objects. gs is not static.
The method above where the problem occurs is:
for(GameUnit gu : this.getBase().getGameState().getAllUnits()){//<---this is the problem line.
//do some stuff...
 }

getAllUnits returns an ArrayList of GameUnits (including the GameUnit calling the method - I don't need an iterator as no objects are deleted or created).

A:

You're really asking the same question as this: Thread-safe iteration over a collection.
The simplest solution is to copy the list before iterating through it:
for(GameUnit gu : new ArrayList<GameUnit>(this.getBase().getGameState().getAllUnits()))

Alternatively you can synchronize on the collection itself (note that for this to work, you also have to synchronize wherever you're modifying the "all units" list):
ArrayList<GameUnit> units = this.getBase().getGameState().getAllUnits())
synchronized (units) {
  ...
}


Q:

Freeze top row office-js

I was wondering if it is posible to freeze the top row of an excel sheet using the office-js api
within excel this feature, aplogies for the dutch installation.

A:

This is not available yet; but definitely is on the road-map. I'll update this thread with the specs and some estimate of the date when it is available.
One could also follow the open-spec branches of the OfficeJS repo to get a view into new features coming along.


Q:

C++ Error - no matching function for call

I am having some problems trying to compile my code because of an error.
It is in function mergeSort , line: merge(a, from, mid, to); :

Invalid arguments ' Candidates are:
     2 merge(#0, #0, #1, #1, #2, #3)
     2 merge(#0, #0, #1, #1, #2) ' no matching function for call to merge(std::vector >&, int&, int&, int&)

    void mergeSort(vector<string> &a, int from, int to)
    {
        if (from == to)
        {
            return;
        }
        int mid = (from + to) / 2;

        mergeSort(a, from, mid);
        mergeSort(a, mid + 1, to);
        merge(a, from, mid, to);

    } // end mergeSort

     void merge(vector<string> &a, int from, int mid, int to)
    {
        int n = to - from + 1;
        vector<string> b(n);
        int i1 = from;
        int i2 = mid + 1;
        int j = 0;

        while (i1 <= mid && i2 <= to)
        {
            if (a[i1].compare(a[i2]) < 0)
            {
                b[j] = a[i1];
                i1++;
            }
            else
            {
                b[j] = a[i2];
                i2++;
            }
            j++;
        }

        while (i1 <= mid)
        {
            b[j] = a[i1];
            i1++;
            j++;
        }

        while (i2 <= to)
        {
            b[j] = a[i2];
            i2++;
            j++;
        }

        for (j = 0; j < n; j++)
        {
            a[from + j] = b[j];
        }
    }

     int main() {
        vector<string> v = {"Apple", "Fruit", "Banana", "apple", "4apples", "applesauce", "3bananas", "\"apple\""}

        //  Print original vector
                cout << "******Original*******"<< endl;
                for (vector<string>::size_type i = 0; i < v.size(); ++i)
                {

                  cout << v[i] << endl;
                }

               mergeSort(v, 0, v.size() - 1);

                cout << "******MERGE SORTED*******"<< endl;
                for (vector<string>::size_type i = 0; i < v.size(); ++i)
                {

                      cout << v[i] << endl;
                }

        }

A:

The standard C++ library has its own std::merge() functions. Those are the candidates you see described in the compiler error as not matching. It does not appear the compiler is even considering your merge() function. This implies that you have not declared your function before trying to use it, and that you have a using namespace std statement in your code.
You need to declare your function. And you need to either get rid of the using statement or else declare your function in its own namespace, and then have mergeSort() be explicit about which namespace to pull merge() from.


Q:

How to check if Mersenne number is prime?

How can I prove that that Mersenne number, number of the type $2^n - 1$ is prime number. One theorem says that if $2^n - 1$ is prime than $n$ is prime number also. But this doesn't work vice versa. For example: $2^{11} - 1$ isn't prime number, although $n = 11$ which is prime number. Is there any way how can I check whether $2^{17} - 1, 2^{23} - 1, 2^{31} - 1 ...$ are primes or not?
Here's one way i find, although I need an explanation:
For $2^{17} - 1$
Let there be $p|2^{17} - 1$
By Fermat theorem we have $p|2^{p-1} - 1$
So $p|2^{lcm(17,p-1)} - 1$ (WHY????)
Least common multiplier can be either 1 or 17. Obviously it's 17. So we have that
$17|p-1$ and $2|p-1$ which is true for every prime number bigger than 2.
Finally we get $34|p-1$ and $p=34k + 1$
Because p is divisor of $2^{17} - 1$ it means it's smaller or equal to $\sqrt{2^{17} - 1}$
Number that satisfy both conditions are {103, 137, 239, 307} (shouldn't I check all numbers in the range of $\sqrt{2^{17} - 1}$ and $2^{17} - 1$? Because $p$ can be in that range) and none of them divides $2^{17} - 1$. Which means that $2^{17} - 1$ is prime.

A:

To the best of my knowledge, the best known test to determine whether a Mersenne number is prime is the Lucas-Lehmer test. If you already know that $p$ is an odd prime (it doesn't work for $M_2 = 3$), let
$U_0 = 4$, and $U_{n+1} \equiv U_n^2 - 2 \pmod {M_p}$.
Then $M_p$ is prime if and only if $U_{p-2} \equiv 0 \pmod {M_p}$.
Taking the modulus at each step, to check the primality of $M_p$, only $2\cdot p$-bit numbers are necessary, thus the proof (or disproof) is computationally feasible even for larger $p$.
The mathematics behind that are more involved than I am ready to explain here.

Regarding the edit - I presume the most important thing is the line with the "why?".
For the assumed prime $p$ dividing $M_{17}$, let $k$ be the order of 2 in $\mathbb{Z}_p^\ast$ (the group of units [non-zero elements] of $\mathbb{Z}_p$).
Then $p \mid 2^n - 1 \iff 2^n \equiv 1 \pmod p \iff k \mid n$. The last can be seen by writing $n = q\cdot k + r\quad, 0 \leqslant r < k$.
So by assumption $k \mid 17$, and by Fermat's theorem, $k \mid (p-1)$. Hence $k \mid (17, p-1)$.

Because $p$ is divisor of $2^{17}−1$ it means it's smaller or equal to $\sqrt{2^{17}−1}$

That's not quite correct as stated, but assuming $M_{17}$ composite, and $p$ its smallest prime divisor, the conclusion $p \leqslant \sqrt{2^{17}-1}$ holds. (Since $M_p \equiv 3 \pmod 4$, we can replace the $\leqslant$ with a $<$.)


Q:

PHP load  data into

<select name="template" id="template">
        <option value="none">Don't use template</option>
        <option value="RWT">Report Abuse</option>
        <option value="renew">Resend Email Codes</option>
    </select>

    <textarea name="body" rows="10" id="content" value="<?php echo $body;?>"ondblclick="select_all('content');" cols="40"></textarea>

....
else if ($template == "renew") {
        $body = "Dear $username,

";
        $body .= "Here is your requested activation code: $activationID

";
        $body .= "Thank you.
";
    }

When I select the option "renew" it doesn't load the data into my textarea.  How can I load option data inside the textarea?

A:

It has to go inside the textarea tag:
<textarea name="body" rows="10" id="content" ondblclick="select_all('content');" cols="40">
  <?php echo $body;?>
</textarea>

Update: as tacone mention in the comments, echo htmlspecialchars($body) would be better because it's the right way to do things -- in this specific case there will be no difference, but other times unless you do it your application will be vulnerable to XSS attacks.


Q:

Calculate average from CSV

I am new to Python and im trying to calculate some averages.
I have a CSV with the following data:
Network,Result
Network 1,100
Network 2,200
Network 3,300
Network 1,101
Network 2,202
Network 3,303

How can i calculate the average for Network 1,Network 2 and Network 3 and create another CSV with the following data:
Network,Average
Network 1,105
Network 2,201
Network 3,301.5

Is seems pretty easy, but im breaking my head over this.
Thnx in advance!

A:

Here's a way to do:
import pandas as pd
df = pd.read_csv(path_to_csv)

(df
.groupby('Network')['Result'].mean()
.rename(columns={"Result": "Average"})
.reset_index()
.to_csv("agg.csv", index=False))

     Network  Average
0  Network 1   100.5
1  Network 2   201.0
2  Network 3   301.5


Q:

Handling a null object in a derived class c# unity

I have a base class called BaseWeather and every weather state derives from this base class
Now BaseWeather contains public ParticleSystem _ParticleSystem; Because most of the weather states can have 1 or more particle systems(Thunderstorm->Rain->Lighting->Tornado)
Now when it comes to the Sunny state of weather there are no particle systems because the "Sunnyness" is handled by light and fog so in my derived class Sunny I did this to try to remedy the fact that there is gonna be a null particle system
try{
            base.ResetEmission();
        }catch{
            if (WeatherSystem.Instance._debugState == DebugLevel.Full) {
                Debug.LogWarning ("Particle System is null at Sunny.cs line 47");
            }
        }

My logic here was using a try block and finding that ResetEmission() dosent work it will just assumes its null debug the warning and it wont affect gameplay
My question is what is the "right" way to handle this scenario

A:

The "right" way would be one of:

Create another base class, e.g. BaseWeatherWithParticleSystem and only inherit from that if you do in fact supply a particle system
Create an interface, e.g. IWeatherParticleSystem and implement that for the classes that need a particle system.

I'd lean to the interface approach. It makes testing easier and more clearly advertises the capabilities of the class. Mind you, you could implement both approaches, e.g.:
public class BaseWeather { ... }
public class BaseWeatherWithParticleSystem : BaseWeather, IWeatherParticleSystem { ... }

As for applying the interface to the base class or the derived class, that depends on the level of support your IDE provides for easily discovering the implemented interfaces from a class reference.
Just beware of trying to handle too much through inheritance and base classes. It's easy to program yourself into a corner trying to make everything fit into an inheritance hierarchy. I find you're often better off implementing things directly and then refactoring common code after you've got the basics set up.
As @maccettura noted in their comment, the "right" way seeks to avoid violating the SOLID principles.


Q:

How to have EMRFS consistent view on S3 buckets with retention policy?

I am using an AWS EMR compute cluster (version 5.27.0) , which uses S3 for data persistence.
This cluster both reads and writes to S3.
S3 has an issue of eventual consistency, because of which after writing data, it cannot be immediately listed. Due to this I use EMRFS with DynamoDB to store newly written paths for immediate listing.
Problem now is that I have to set a retention policy on S3, because of which data more than a month old will get deleted from S3. However, in doing so , the data does not get deleted from EMRFS DynamoDB table, leading to consistency issues.
My question is , how can I ensure that on setting the retention policy in S3, the same paths get deleted from the DynamoDB table?
One naive solution I have come up with is to define a Lambda, which fires periodically, and sets TTL of say 1 day on the DynamoDB records manually. Is there a better approach than this ?

A:

You can configure DynamoDB with same expiration policy as your S3 objects have
https://aws.amazon.com/blogs/aws/new-manage-dynamodb-items-using-time-to-live-ttl/
and in this case, you ensure both DynamoDB and S3 have the same existing objects


Q:

Websphere MQ classes needed in Websphere Application Server

So I have a JMS application deployed on a Webpshere Application Server, this application try to connect to the queue directy using a com.ibm.mq.jms.MQConnectionFactory and I wonder if I should include Websphere MQ jars in my application or should they be provided by Websphere Application Server. My application is currenty without them and I don't have a ClassNotFoundException but I do get issues (I have a SIB_MESSAGE error that appear), could this be related to the fact that my server is on PARENT_LAST or to an incompatibility between the WAS server version and the WMQ server version ?
Should I include Websphere MQ jars in my application ? Could this help with my issues or make it worse ?
Thanks for any help.

A:

Do not bundle WebSphere MQ jar files within your application. This will not be supported by IBM and is very bad practice.
You must use the WebSphere MQ classes for JMS that are shipped within WebSphere Application Server (which are included within the WebSphere MQ JCA resource adapter). This way, the version of the classes for JMS you use will be updated as and when you apply WebSphere Application Server maintenance.
Any version of the WebSphere MQ JCA resource adapter shipped within WebSphere Application Server can connect to any v7.x or v8 queue manager.
Without further details on the exact error you are receiving, I cannot help further.


Q:

How to get a list of Objects instead of a list of Maps in gremlin-javascript

Hi I am now using gremlin -javascript to do some queries in AWS neptune DB.
I have a query like
[errRelatedTicket, relatedTicket] = await to(g.V().hasId(a).in_('r').valueMap(true).toList());

then I get a list of map like:
[
 Map {
   id: 1
 },
 Map {
   id: 2
 },
]

But can I use gremlin query to get id and properties in key/value pairs directly instead?
what I expect is:
[
  { id: 1 },
  { id: 2 },
]

A:

I don't know "gremlin-javascript", you can research more in the document. But I know there's a simple way to do the conversion in plain javascript, use .map and Object.fromEntries. Hope you'll find a better way.

var listMap = [
  new Map([[ 'id', 1 ]]),
  new Map([[ 'id', 2 ]]),
];

var listObject = listMap.map(m => Object.fromEntries(m));

console.log(listObject);


Q:

Loading speed vs memory: how to efficiently load large arrays from h5 file

I have been facing the following issue: I have to loop over num_objects = 897 objects, for every single one of which I have to use num_files = 2120 h5 files. The files are very large, each being 1.48 GB and the content of interest to me is 3 arrays of floats of size 256 x 256 x 256 contained in every file (v1,v2 and v3). This is to say, the loop looks like:
for i in range(num_objects):
    ...
    for j in range(num_files):
       some operation with the three 256 x 256 x 256 arrays in each file

and my current way of loading them is by doing the following in the innermost loop:
f = h5py.File('output_'+str(q)+'.h5','r')
key1 = np.array(f['key1'])
v1=key1[:,:,:,0]
v2=key2[:,:,:,1]
v3=key3[:,:,:,2]

The above option of loading the files every time for every object is obviously very slow. On the other hand, loading all files at once and importing them in a dictionary results in excessive use of memory and my job gets killed. Some diagnostics:

The above way takes 0.48 seconds per file, per object, resulting in a total of 10.5 days (!) spent only on this operation.
I tried exporting key1 to npz files, but it was actually slower by 0.7 seconds per file.
I exported v1,v2 and v3 individually for every file to npz files (i.e. 3 npz files for each h5 file), but that saved me only 1.5 day in total.

Does anyone have some other idea/suggestion I could try to be fast and at the same time not limited by excessive memory usage?

A:

If I understand, you have 2120 .h5 files. Do you only read the 3 arrays in dataset f['key1'] for each file? (or are there other datasets?) If you only/always read f['key1'], that's a bottleneck you can't program around. Using a SSD will help (because I/O is faster than HDD). Otherwise, you will have to reorganize your data. The amount of RAM on your system will determine the number of arrays you can read simultaneously. How much RAM do you have?
You might gain a little speed with a small code change. v1=key1[:,:,:,0] returns v1 as an array (same for v2 and v3).  There's no need to read dataset f['key1'] into an array. Doing that doubles your memory footprint. (BTW, Is there a reason to convert your arrays to a dictionary?)
The process below only creates 3 arrays by slicing v1,v2,v3 from the h5py f['key1']object. It will reduce your memory footprint for each loop by 50%.
f = h5py.File('output_'+str(q)+'.h5','r')
key1 = f['key1']
## key1 is returned as a h5py dataset OBJECT, not an array
v1=key1[:,:,:,0]
v2=key2[:,:,:,1]
v3=key3[:,:,:,2]

On the HDF5 side, since you always slice out the last axis, your chunk parameters might improve I/O. However, if you want to change the chunk shape, you will have to recreate the .h5 files. So, that will probably not save time (at least in the short-term).


Q:

Converse Noetherian Relation

I have looked around and cannot find the answer so I ask here. It is well known that if $R$ is noetherian then $R[X]$ is too, but what about the converse? If $R[X]$ is noetherian can we say $R$ is? My gut feeling says no and the fact it seems so hard to find an answer makes me feel certain about it.

A:

The converse is a straightforward consequence of the following fact:

Let $S$ be a Noetherian ring and $I \subset S$ an ideal. Then the factor ring $S/I$ is Noetherian.

Now, take $S=R[X]$ , $I=(X)$, and recall that $R[X]/(X) \cong R$.


Q:

How can I selectively delete a Start Menu folder with NSIS?

I am using NSIS to create install and uninstall wizards to my rather simple app for Windows.
The situation is, my NSIS script creates a shortcut to the app in the Start Menu folder for the installation wizard. So far no problem. Other apps (related with mine) install their shourcts in the same Start Menu Folder too.
The problem is in the uninstall process. I can delete my shortcuts without a problem but, what about of the folder in the Start Menu? I cannot delete it if there are apps alredy there but I would like it to be removed if the folder is empty.
How can I check using the NSIS script if the folder is empty and therefore condition if the deletion of the folder has to happen or not?
Although is not vital I don't like to have empty useless folders cluttering my Start Menu view.
Thank you very much in advance!
Julen.

A:

RMDir "$SMPrograms\yourfolder" will only delete the folder if it is empty


Q:

Blender 2.8 How do I fix the gloss on this mesh?

I’m using normal maps here, Is it the faulty map or something else that’s causing this strange effect?
How would I turn this into something like this:

 Sort of a matte effect

A:

Some of the point:

You can change the strength of normal by using normal map node
The second wood of your picture seems to have a clearcoat on it, there is an attribute to do that effect too
The roughness change how light reflective

Try it your self, and most of the time you will get specular or roughness or smoothness(?) image map as well. You can use those images as input


Q:

Defining variables in cfscript ColdFusion?

I tried to rewrite my Application.cfc and other .cfc files in my system with cfscript. There is few things that I'm not sure how they work in cfscript. I'm wondering about defining variables inside of the functions. For example onRequestStart() function looks like this:
function onRequestStart(required string thePage) returntype="boolean" output="false" {
        var request.appCode = "MyApp";
        var request.appName = "Single Page Application";
        var page = listLast(arguments.thePage,"/");
        var onApplicationStart();

        if(!listFindNoCase("Home.cfm,Auth.cfc",page)){
            if(structKeyExists(SESSION, "loggedin") AND SESSION.loggedin EQ false){
                location(url="https://www.myapp.org", addToken="false");
            }
        }

        return true;
    }

Do I need to use var word in situations where I'm defining request/session variables? If I do what is the best practice, use var word or use local.variablename? Is local and variables same in cfscript?

A:

var is used only for local variables. That means variables which are/should not be accessible outside the function definition. Session & Request are accessible to each session & request respectively. Putting them on var scope will give terrible results.
You can use either var or local, both have 'local' scope. Variables is the page scope and any variable defined in the Variables scope will be accessible to all functions in the CFC.
function onRequestStart(required string thePage) returntype="boolean" output="false" {
    request.appCode = "MyApp";
    request.appName = "Single Page Application";
    var page = listLast(arguments.thePage,"/");
  //this is a function call and not variable declaration.
  onApplicationStart();

    if(!listFindNoCase("Home.cfm,Auth.cfc",page)){
        if(structKeyExists(SESSION, "loggedin") AND SESSION.loggedin EQ false){
            location(url="https://www.myapp.org", addToken="false");
        }
    }

    return true;
}

A:

var is not equal to the <cfset> tag, i.e. you can't do a simple search & replace when switching to CFScript syntax.
var is only used for local variable definitions. This means, setting structure and array items, like request, session and other scope variables should not be prefixed by var.
Also, function calls must be written without preceding var.
local and var both refer to the local scope. Though note, as mentioned above, if you want to define variables via local.something the var keyword is also not needed.
variables, in contrary to local, refers to the page scope, which is accessible from everywhere within the component and any included pages.
For more info on the different scopes, you should read the Adobe docs.


Q:

Создание рамки из фрагмента изображения

В общем хочу чтобы из куска картинки сделать полноценную рамку для изображения, а на странице уже было изображение и при выборе фрагмента по нажатию изображение становилось в рамке по его размеру.
Простыми словами сделать из
Вот это

А дальше подогнать готовую рамку по размеру картинки

A:

Собственно это не сложно - берём ваш отрезок - встраиваем его в svg - делаем mask с двух сторон - и крутим его для получения нужной формы - результат увидите при нажатии на Выполнить код

<svg width="350px" viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg">
 <defs>
   <style>
     .m1{
       transform-origin: center;
       transform: rotate(90deg)translate(0,500px)
     }
     .m2{
       transform-origin: center;
       transform:translate(0,500px)
     }
     .m3{
       transform-origin: center;
       transform: rotate(-90deg)translate(0,500px)
     }
     .m4{
       transform-origin: center;
       transform: rotate(-180deg)translate(0,500px)
     }
   </style>
   <mask id="m1">
     <rect width="600px" height="100px" fill="#fff"></rect>
       <path d="M600,0 600,100 500,0z"/>
       <path d="M0,0 0,100 100,0z"/>
   </mask>
  </defs>

  <image href="https://i.stack.imgur.com/wrGO7.jpg" width="410px" height="410px" x="95" y="95"/>
  <g>
  <image href="https://i.stack.imgur.com/0E5BJ.png"
         width="600" height="100" preserveAspectRatio="none"
         class="m1" mask="url(#m1)" />

   <image href="https://i.stack.imgur.com/0E5BJ.png"
         width="600" height="100px" preserveAspectRatio="none"
         class="m2" mask="url(#m1)"/>

   <image href="https://i.stack.imgur.com/0E5BJ.png"
         width="600" height="100px" preserveAspectRatio="none"
         class="m3" mask="url(#m1)"/>

     <image href="https://i.stack.imgur.com/0E5BJ.png"
         width="600" height="100px" preserveAspectRatio="none"
         class="m4" mask="url(#m1)"/>
</g>
</svg>

Второй вариант - если надо горизонтальное фото

<svg viewBox="0 1 980 755" xmlns="http://www.w3.org/2000/svg" width="350">
  <defs>
   <mask id="m1">
        <rect width="100%" height="100%" fill="#fff" />
        <path d="M0,0 0,100 100,100z"/>
        <path d="M980,0 980,100 880,100z "/>
    </mask>

    <mask id="m2">
     <rect width="100%" height="100%" fill="#fff" />
     <path  d="M0,668 100,668 0,768z" />
     <path  d="M880,668 980,668 980,768z" />
    </mask>
    <style>
      .image3{
        transform-origin:top left;
        transform: rotate(90deg)translate(-200px,-100px);
      }
      .image4{
        transform-origin:top left;
        transform: rotate(90deg)translate(-200px,-980px);
      }
    </style>
  </defs>

 <image href="https://i.stack.imgur.com/vFkd0.jpg"
        width="980" height="755" x="0" y="0"/>

    <image href="https://i.stack.imgur.com/0E5BJ.png"
         preserveAspectRatio="none"
         width="100%" height="100px"
         x="0" y="0" class="image3"/>

    <image href="https://i.stack.imgur.com/0E5BJ.png"
         preserveAspectRatio="none"
         width="100%" height="100px"
         x="0" y="0" class="image4"/>

    <image href="https://i.stack.imgur.com/0E5BJ.png"
         preserveAspectRatio="none"
         width="100%" height="100px"
         x="0" y="0" mask="url(#m1)"/>

  <image href="https://i.stack.imgur.com/0E5BJ.png"
         preserveAspectRatio="none"
         width="100%" height="100px"
         x="0" y="665" mask="url(#m2)"/>

</svg>


Q:

What would be the regex for matching an alphanumeric string with 4 digits & 1 alphabet?

For example, it should allow strings like '1234n' , '1234a' . Max string size is 5 and it should only allow a sequence of 4 digits followed by a character.

A:

You can do:
^\d{4}[A-Za-z]$

^\d{4} matches 4 digits at the start
[A-Za-z]$ matches any single alphabetic character at the end