Programs & Examples On #Pdo

PDO (PHP Data Objects) is a database abstraction layer(interface) for PHP. It works with most database systems.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

If you want to insert NULL only when the value is empty or '', but insert the value when it is available.

A) Receives the form data using POST method, and calls function insert with those values.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evaluates if a field was not filled up by the user, and inserts NULL if that's the case.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

For instance, if the user doesn't input anything on the productName field of the form, then $productName will be SET but EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.

Tested on PHP 5.5.17

Good luck,

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP ON Mac, I solve my problem by renaming

/Applications/MAMP/tmp/mysql/mysql.sock.lock

to

/Applications/MAMP/tmp/mysql/mysql.sock

PDO closing connection

I created a derived class to have a more self-documented instruction instead of $conn=null;.

class CMyPDO extends PDO {
    public function __construct($dsn, $username = null, $password = null, array $options = null) {
        parent::__construct($dsn, $username, $password, $options);
    }

    static function getNewConnection() {
        $conn=null;
        try {
            $conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
        }
        catch (PDOException $exc) {
            echo $exc->getMessage();
        }
        return $conn;
    }

    static function closeConnection(&$conn) {
        $conn=null;
    }
}

So I can call my code between:

$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);

PDOException “could not find driver”

I had the same issue. The solution depends on OS. In my case, i have debian, so to solve it:

  • Updated my php version from (php5 to php7)
  • Install php-mysql and php7.0-mysql

    apt-get install php-mysql
    apt-get install php7.0-mysql
    
  • I edited my php.ini locate at /etc/php/7.0/apache2/php.ini

    uncomment the line : extension=php_pdo_mysql.dll
    
  • Then restart apache:

    service apache2 restart
    

This solves my problem

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

My case was that i was using RDS (mysql db verion 8) of AWS and was connecting my application through EC2 (my php code 5.6 was in EC2).

Here in this case since it is RDS there is no my.cnf the parameters are maintained by PARAMETER Group of AWS. Refer: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html

so what i did was:

  1. Created a new Parameter group and then edited them.

  2. Searched all character-set parameters. These are blank by default. edit them individually and select utf8 from drop down list.

character_set_client, character_set_connection, character_set_database, character_set_server

  1. SAVE

And then most important, Rebooted RDS instance.

This has solved my problem and connection from php5.6 to mysql 8.x was working great.

hope this helps.

Please view this image for better understanding. enter image description here

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

PDO does support this (as of 2020). Just do a query() call on a PDO object as usual, separating queries by ; and then nextRowset() to step to the next SELECT result, if you have multiple. Resultsets will be in the same order as the queries. Obviously think about the security implications - so don't accept user supplied queries, use parameters, etc. I use it with queries generated by code for example.

$statement = $connection->query($query);
do {
  $data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());

In PHP with PDO, how to check the final SQL parametrized query?

What I did to print that actual query is a bit complicated but it works :)

In method that assigns variables to my statement I have another variable that looks a bit like this:

$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);

Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens

What it does is a simply replace tokens with values when the real PDO assignment happens.

I hope I did not confuse you and at least pointed you in right direction.

PDO Prepared Inserts multiple rows in single query

I had the same problem and this is how i accomplish for myself, and i made a function for myself for it ( and you can use it if that helps you).

Example:

INSERT INTO countries (country, city) VALUES (Germany, Berlin), (France, Paris);

$arr1 = Array("Germany", "Berlin");
$arr2 = Array("France", "France");

insertMultipleData("countries", Array($arr1, $arr2));


// Inserting multiple data to the Database.
public function insertMultipleData($table, $multi_params){
    try{
        $db = $this->connect();

        $beforeParams = "";
        $paramsStr = "";
        $valuesStr = "";

        for ($i=0; $i < count($multi_params); $i++) { 

            foreach ($multi_params[$i] as $j => $value) {                   

                if ($i == 0) {
                    $beforeParams .=  " " . $j . ",";
                }

                $paramsStr .= " :"  . $j . "_" . $i .",";                                       
            }

            $paramsStr = substr_replace($paramsStr, "", -1);
            $valuesStr .=  "(" . $paramsStr . "),"; 
            $paramsStr = "";
        }


        $beforeParams = substr_replace($beforeParams, "", -1);
        $valuesStr = substr_replace($valuesStr, "", -1);


        $sql = "INSERT INTO " . $table . " (" . $beforeParams . ") VALUES " . $valuesStr . ";";

        $stmt = $db->prepare($sql);


        for ($i=0; $i < count($multi_params); $i++) { 
            foreach ($multi_params[$i] as $j => &$value) {
                $stmt->bindParam(":" . $j . "_" . $i, $value);                                      
            }
        }

        $this->close($db);
        $stmt->execute();                       

        return true;

    }catch(PDOException $e){            
        return false;
    }

    return false;
}

// Making connection to the Database 
    public function connect(){
        $host = Constants::DB_HOST;
        $dbname = Constants::DB_NAME;
        $user = Constants::DB_USER;
        $pass = Constants::DB_PASS;

        $mysql_connect_str = 'mysql:host='. $host . ';dbname=' .$dbname;

        $dbConnection = new PDO($mysql_connect_str, $user, $pass);
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return $dbConnection;
    }

    // Closing the connection
    public function close($db){
        $db = null;
    }

If insertMultipleData($table, $multi_params) returns TRUE, your data has been inserted to your database.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For Centos I was missing php-mysql library:

yum install php-mysql

service httpd restart

There is no need to enable any extension in php.ini, it is loaded by default.

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

PDO error message?

Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:

$field1 = 'foo';
$field2 = 'bar';

$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);

$insert_QUERY->execute();

$databaseErrors = $insert_QUERY->errorInfo();

if( !empty($databaseErrors) ){  
    $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
    $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         

/* 
 $errorLogMsg will return something like: 
 error info:  
 Array(
  [0] => 42000
  [1] => 1064
  [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
 )
*/
} else {
    # no SQL errors.
}

PHP PDO: charset, set names?

You'll have it in your connection string like:

"mysql:host=$host;dbname=$db;charset=utf8"

HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

$dbh = new PDO("mysql:$connstr",  $user, $password);
$dbh->exec("set names utf8");

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

PHP PDO with foreach and fetch

A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.

You can close the cursor after the foreach and execute the statement again:

$users       = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

$users->execute();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Or you could cache using tailored CachingIterator with a fullcache:

$users       = $dbh->query($sql);

$usersCached = new CachedPDOStatement($users);

foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

You find the CachedPDOStatement class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.

How to read fetch(PDO::FETCH_ASSOC);

To read the result you can read it like a simple php array.

For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

Real escape string and PDO

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

MySQL check if a table exists without throwing an exception

I don't know the PDO syntax for it, but this seems pretty straight-forward:

$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

Assuming you did the normal installation with virtual box, vagrant etc.. This can happen to new people. PHP can be installed on your PC but all the modules PHP for your laravel project is on your VM So to access your VM, go to your homestead folder and type: vagrant ssh

then to go your project path and execute the php artisan migrate.

Checking for empty result (php, pdo, mysql)

Even though this is an old thread, I thought I would weigh in as I had to deal with this lately.

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today))) 
{
    $db = null ;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

I had a similar issue when trying to migrate a Drupal website from one local host to another. From Mac running XAMMP to Windows running WAMP.

This was the error message I kept getting when trying to access the pages of the website.

PDOException: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. 
in drupal_get_installed_schema_version() (line 155 of C:\wamp\www\chia\includes\install.inc).

In settings.php, I've changed everything correctly, database name, user and password.

$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'mydatabasename',
      'username' => 'mydbusername',
      'password' => 'mydbpass',
      'host' => 'localhost',
      'port' => '8889',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

After a couple of hours of mindless google searching I've changed the port to a empty value:

'port' => '',

And after that the site loaded properly.

Getting raw SQL query string from PDO prepared statements

/**
 * Replaces any parameter placeholders in a query with the value of that
 * parameter. Useful for debugging. Assumes anonymous parameters from 
 * $params are are in the same order as specified in $query
 *
 * @param string $query The sql query with parameter placeholders
 * @param array $params The array of substitution parameters
 * @return string The interpolated query
 */
public static function interpolateQuery($query, $params) {
    $keys = array();

    # build a regular expression for each parameter
    foreach ($params as $key => $value) {
        if (is_string($key)) {
            $keys[] = '/:'.$key.'/';
        } else {
            $keys[] = '/[?]/';
        }
    }

    $query = preg_replace($keys, $params, $query, 1, $count);

    #trigger_error('replaced '.$count.' keys');

    return $query;
}

PHP 7 RC3: How to install missing MySQL PDO

['class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost:3306;dbname=testdb',
    'username' => 'user',
    'password' => 'password',
    'charset' => 'utf8',]

It's simple: Just provide the port number along with the host name and set default sock path to your mysql.sock file path in php.ini which the server is running on.

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I don't know why the above solution and the official solution which is adding

Schema::defaultStringLength(191);

in AppServiceProvider didn't work for me. What worked for was editing the database.php file in config folder. Just edit

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

to

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',

and it should work, although you will be unable to store extended multibyte characters like emoji.

I did it with Laravel 5.7. Hope it helps.

php, mysql - Too many connections to database error

The error SQLSTATE[HY000] [1040] Too many connections is an SQL error, and has to do with the sql server. There could be other applications connecting to the server. The server has a maximum available connections number.

If you have phpmyadmin, you can use the 'variables' tab to check what the setting is.

You can also query the status table like so:

show status like '%onn%';

Or some variance on that. check the manual for what variables there are

(be aware, 'connections' is not the current connections, check that link :) )

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

Personally, I wouldn't bother; I'd just rename the column.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

What is the difference between bindParam and bindValue?

For the most common purpose, you should use bindValue.

bindParam has two tricky or unexpected behaviors:

  • bindParam(':foo', 4, PDO::PARAM_INT) does not work, as it requires passing a variable (as reference).
  • bindParam(':foo', $value, PDO::PARAM_INT) will change $value to string after running execute(). This, of course, can lead to subtle bugs that might be difficult to catch.

Source: http://php.net/manual/en/pdostatement.bindparam.php#94711

PHP PDO returning single row

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

Row count with PDO

For straight queries where I want a specific row, and want to know if it was found, I use something like:

function fetchSpecificRow(&$myRecord) {
    $myRecord = array();
    $myQuery = "some sql...";
    $stmt = $this->prepare($myQuery);
    $stmt->execute(array($parm1, $parm2, ...));
    if ($myRecord = $stmt->fetch(PDO::FETCH_ASSOC)) return 0;
    return $myErrNum;
}

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

How to debug PDO database queries?

Searching internet I found this as an acceptable solution. A different class is used instead of PDO and PDO functions are called through magic function calls. I am not sure this creates serious performance problems. But it can be used until a sensible logging feature is added to PDO.

So as per this thread, you can write a wrapper for your PDO connection which can log and throws an exception when you get a error.

Here is simple example:

class LoggedPDOSTatement extends PDOStatement    {

function execute ($array)    {
    parent::execute ($array);
    $errors = parent::errorInfo();
    if ($errors[0] != '00000'):
        throw new Exception ($errors[2]);
    endif;
  }

}

so you can use that class instead of PDOStatement:

$this->db->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('LoggedPDOStatement', array()));

Here a mentioned PDO decorator implementation:

class LoggedPDOStatement    {

function __construct ($stmt)    {
    $this->stmt = $stmt;
}

function execute ($params = null)    {
    $result = $this->stmt->execute ($params); 
    if ($this->stmt->errorCode() != PDO::ERR_NONE):
        $errors = $this->stmt->errorInfo();
        $this->paint ($errors[2]);
    endif;
    return $result;
}

function bindValue ($key, $value)    {
    $this->values[$key] = $value;    
    return $this->stmt->bindValue ($key, $value);
}

function paint ($message = false)    {
    echo '<pre>';
    echo '<table cellpadding="5px">';
    echo '<tr><td colspan="2">Message: ' . $message . '</td></tr>';
    echo '<tr><td colspan="2">Query: ' . $this->stmt->queryString . '</td></tr>';
    if (count ($this->values) > 0):
    foreach ($this->values as $key => $value):
    echo '<tr><th align="left" style="background-color: #ccc;">' . $key . '</th><td>' . $value . '</td></tr>';
    endforeach;
    endif;
    echo '</table>';
    echo '</pre>';
}

function __call ($method, $params)    {
    return call_user_func_array (array ($this->stmt, $method), $params); 
}

}

PDO mysql: How to know if insert was successful

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }

How to get the total number of rows of a GROUP BY query?

I don't use PDO for MySQL and PgSQL, but I do for SQLite. Is there a way (without completely changing the dbal back) to count rows like this in PDO?

Accordingly to this comment, the SQLite issue was introduced by an API change in 3.x.

That said, you might want to inspect how PDO actually implements the functionality before using it.

I'm not familiar with its internals but I'd be suspicious at the idea that PDO parses your SQL (since an SQL syntax error would appear in the DB's logs) let alone tries to make the slightest sense of it in order to count rows using an optimal strategy.

Assuming it doesn't indeed, realistic strategies for it to return a count of all applicable rows in a select statement include string-manipulating the limit clause out of your SQL statement, and either of:

  1. Running a select count() on it as a subquery (thus avoiding the issue you described in your PS);
  2. Opening a cursor, running fetch all and counting the rows; or
  3. Having opened such a cursor in the first place, and similarly counting the remaining rows.

A much better way to count, however, would be to execute the fully optimized query that will do so. More often than not, this means rewriting meaningful chunks of the initial query you're trying to paginate -- stripping unneeded fields and order by operations, etc.

Lastly, if your data sets are large enough that counts any kind of lag, you might also want to investigate returning the estimate derived from the statistics instead, and/or periodically caching the result in Memcache. At some point, having precisely correct counts is no longer useful...

How do I enable php to work with postgresql?

For debian/ubuntu install

sudo apt-get install php-pgsql

PDO with INSERT INTO through prepared statements

Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.

    <?php
    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    try {
        $statement = $link->prepare("INERT INTO testtable(name, lastname, age)
            VALUES(?,?,?)");

        $statement->execute(array("Bob","Desaunois",18));
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    ?>

In the following code instead of INSERT INTO it says INERT.

this is the error I got.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1

When I "fix" the issue, it works as it should. Thanks alot everyone!

Can I bind an array to an IN() condition?

A little editing about the code of Schnalle

<?php
$ids     = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids)-1, '?'));

$db   = new PDO(...);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN(' . $inQuery . ')'
);

foreach ($ids as $k => $id)
    $stmt->bindValue(($k+1), $id);

$stmt->execute();
?>

//implode(',', array_fill(0, count($ids)-1), '?')); 
//'?' this should be inside the array_fill
//$stmt->bindValue(($k+1), $in); 
// instead of $in, it should be $id

mysqli or PDO - what are the pros and cons?

Edited answer.

After having some experience with both these APIs, I would say that there are 2 blocking level features which renders mysqli unusable with native prepared statements.
They were already mentioned in 2 excellent (yet way underrated) answers:

  1. Binding values to arbitrary number of placeholders
  2. Returning data as a mere array

(both also mentioned in this answer)

For some reason mysqli failed with both.
Nowadays it got some improvement for the second one (get_result), but it works only on mysqlnd installations, means you can't rely on this function in your scripts.

Yet it doesn't have bind-by-value even to this day.

So, there is only one choice: PDO

All the other reasons, such as

  • named placeholders (this syntax sugar is way overrated)
  • different databases support (nobody actually ever used it)
  • fetch into object (just useless syntax sugar)
  • speed difference (there is none)

aren't of any significant importance.

At the same time both these APIs lacks some real important features, like

  • identifier placeholder
  • placeholder for the complex data types to make dynamical binding less toilsome
  • shorter application code.

So, to cover the real life needs, one have to create their own abstraction library, based on one of these APIs, implementing manually parsed placeholders. In this case I'd prefer mysqli, for it has lesser level of abstraction.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

Are PDO prepared statements sufficient to prevent SQL injection?

Personally I would always run some form of sanitation on the data first as you can never trust user input, however when using placeholders / parameter binding the inputted data is sent to the server separately to the sql statement and then binded together. The key here is that this binds the provided data to a specific type and a specific use and eliminates any opportunity to change the logic of the SQL statement.

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

PDOException SQLSTATE[HY000] [2002] No such file or directory

In my case I had to remove the bootstrap/cache folder and try it again.

My cenario was after a server migration.

How can I properly use a PDO object for a parameterized SELECT query

Method 1:USE PDO query method

$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

Getting Row Count

$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';

Method 2: Statements With Parameters

$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Method 3:Bind parameters

$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Want to know more look at this link

php pdo: get the columns name of a table

I solve the problem the following way (MySQL only)

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

Connect to SQL Server through PDO using SQL Server Driver

try
{

    $conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e)
{

    $e->getMessage();

}

Copy text from nano editor to shell

The thread is quite old, but today I humbled around with the same question and all the mentioned solutions above did not help. As I wished to copy long lines my solution is - acording to what @themisterunknown wrote above - outside nano. I used awk!

awk '{ if (NR==87) print $0 }' filename

where NR==[line number] and $0 is complete line.

How to use target in location.href

Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?

How can I simulate a click to an anchor tag?

This would work in the cases where the window.open did not work

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Delaying function in swift

For adding argument to delay function.

First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.

let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)

Then in the called function

func functionHereWithArgument (timer : NSTimer)
{
    if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
    {
         let argumentInt : Int = (userInfo[argumentInt] as! Int)
    }
}

XmlWriter to Write to a String Instead of to a File

Guys don't forget to call xmlWriter.Close() and xmlWriter.Dispose() or else your string won't finish creating. It will just be an empty string

Conversion failed when converting the varchar value to data type int in sql

Try this one -

CREATE PROC [dbo].[getVoucherNo]
AS BEGIN

     DECLARE 
            @Prefix VARCHAR(10) = 'J'
          , @startFrom INT = 1
          , @maxCode VARCHAR(100)
          , @sCode INT

     IF EXISTS(
          SELECT 1 
          FROM dbo.Journal_Entry
     ) BEGIN

          SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100)) 
          FROM dbo.Journal_Entry;

          SELECT @Prefix + 
               CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
               CAST(@maxCode AS VARCHAR(100))

     END
     ELSE BEGIN

          SELECT (@Prefix + CAST(@startFrom AS VARCHAR)) 

     END

END

Git - How to fix "corrupted" interactive rebase?

On Windows, if you are unwilling or unable to restart the machine see below.

Install Process Explorer: https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

In Process Explorer, Find > File Handle or DLL ...

Type in the file name mentioned in the error (for my error it was 'git-rebase-todo' but in the question above, 'done').

Process Explorer will highlight the process holding a lock on the file (for me it was 'grep').

Kill the process and you will be able to abort the git action in the standard way.

handling dbnull data in vb.net

   VB.Net
   ========
    Dim da As New SqlDataAdapter
    Dim dt As New DataTable
    Call conecDB()        'Connection to Database
    da.SelectCommand = New SqlCommand("select max(RefNo) from BaseData", connDB)

    da.Fill(dt)

    If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = "" Then
        MsgBox("datbase is null")

    ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> "" Then
        MsgBox("datbase have value")

    End If

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

How to get the wsdl file from a webservice's URL

By postfixing the URL with ?WSDL

If the URL is for example:

http://webservice.example:1234/foo

You use:

http://webservice.example:1234/foo?WSDL

And the wsdl will be delivered.

Android Material and appcompat Manifest merger failed

This issue mainly happened for old dependencies.

There have 2 solution:

First one:

Update all old dependencies and ClassPaths from Project level gradle files.

classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'

Second one:

Your project Migrate to AndroidX

From Android Studio Menu -> Refanctor -> Migrate to AndroidX

Thanks, let me know if anyone help from this answer.

How can I create numbered map markers in Google Maps V3?

This how I do it in V3:

I start by loading the google maps api and within the callback method initialize() I load MarkerWithLabel.js that I found here:

function initialize() {

            $.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){

            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(currentLat, currentLng),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: false,
                mapTypeControl: false
            };

            var map = new google.maps.Map(document.getElementById('mapholder'),
                    mapOptions);

            var bounds = new google.maps.LatLngBounds();

            for (var i = 0; i &lt; mapData.length; i++) {
                createMarker(i+1, map, mapData[i]); <!-- MARKERS! -->
                extendBounds(bounds, mapData[i]);
            }
            map.fitBounds(bounds);
            var maximumZoomLevel = 16;
            var minimumZoomLevel = 11;
            var ourZoom = defaultZoomLevel; // default zoom level

            var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                if (this.getZoom(map.getBounds) &gt; 16) {
                    this.setZoom(maximumZoomLevel);
                }
                google.maps.event.removeListener(blistener);
            });
            });
        }

        function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places&amp;sensor=false&amp;callback=initialize";
            document.body.appendChild(script);
        }

        window.onload = loadScript;

    </script> 

I then create the markers with createMarker():

function createMarker(number, currentMap, currentMapData) {

   var marker = new MarkerWithLabel({
       position: new google.maps.LatLng(currentMapData[0], currentMapData[1]),
                 map: currentMap,
                 icon: '/img/sticker/empty.png',
                 shadow: '/img/sticker/bubble_shadow.png',
                 transparent: '/img/sticker/bubble_transparent.png',
                 draggable: false,
                 raiseOnDrag: false,
                 labelContent: ""+number,
                 labelAnchor: new google.maps.Point(3, 30),
                 labelClass: "mapIconLabel", // the CSS class for the label
                 labelInBackground: false
                });
            }

Since I added mapIconLabel class to the marker I can add some css rules in my css:

.mapIconLabel {
    font-size: 15px;
    font-weight: bold;
    color: #FFFFFF;
    font-family: 'DINNextRoundedLTProMediumRegular';
}

And here is the result:

MarkerWithIconAndLabel

How can I tell jaxb / Maven to generate multiple schema packages?

The following works for me, after much trial

<plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>jaxb2-maven-plugin</artifactId>
         <version>2.1</version>
         <executions>
            <execution>
              <id>xjc1</id>
              <goals>
                  <goal>xjc</goal>
              </goals>
             <configuration>
                <packageName>com.mycompany.clientSummary</packageName>
               <sourceType>wsdl</sourceType>
                <sources>
                <source>src/main/resources/wsdl/GetClientSummary.wsdl</source>
                </sources>
                <outputDirectory>target/generated-sources/xjb</outputDirectory>
                 <clearOutputDir>false</clearOutputDir>
            </configuration>
          </execution>

          <execution>
             <id>xjc2</id>
             <goals>
                 <goal>xjc</goal>
             </goals>
             <configuration>
                <packageName>com.mycompany.wsclient.employerProfile</packageName>
                <sourceType>wsdl</sourceType>
                <sources>
                <source>src/main/resources/wsdl/GetEmployerProfile.wsdl</source>
                </sources>
                <outputDirectory>target/generated-sources/xjb</outputDirectory>
                <clearOutputDir>false</clearOutputDir>
         </configuration>
         </execution>

         <execution>
            <id>xjc3</id>
            <goals>
                <goal>xjc</goal>
            </goals>
            <configuration>
                <packageName>com.mycompany.wsclient.producersLicenseData</packageName>
                <sourceType>wsdl</sourceType>
                <sources>
                <source>src/main/resources/wsdl/GetProducersLicenseData.wsdl</source>
                </sources>
                <outputDirectory>target/generated-sources/xjb</outputDirectory>
                <clearOutputDir>false</clearOutputDir>
            </configuration>
        </execution>


     </executions>
  </plugin>

Can we cast a generic object to a custom object type in javascript?

This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

CustomObject.create = function (obj) {
    var field = new CustomObject();
    for (var prop in obj) {
        if (field.hasOwnProperty(prop)) {
            field[prop] = obj[prop];
        }
    }

    return field;
}

Use like this

var typedObj = CustomObject.create(genericObj);

Regular expression matching a multiline block of text

find:

^>([^\n\r]+)[\n\r]([A-Z\n\r]+)

\1 = some_varying_text

\2 = lines of all CAPS

Edit (proof that this works):

text = """> some_Varying_TEXT

DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF
GATACAACATAGGATACA
GGGGGAAAAAAAATTTTTTTTT
CCCCAAAA

> some_Varying_TEXT2

DJASDFHKJFHKSDHF
HHASGDFTERYTERE
GAGAGAGAGAG
PPPPPAAAAAAAAAAAAAAAP
"""

import re

regex = re.compile(r'^>([^\n\r]+)[\n\r]([A-Z\n\r]+)', re.MULTILINE)
matches = [m.groups() for m in regex.finditer(text)]

for m in matches:
    print 'Name: %s\nSequence:%s' % (m[0], m[1])

Git undo local branch delete

Follow these Steps:

1: Enter:

git reflog show 

This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back

2: create a branch name with the Sha-1 ID you selected eg: 8c87714

git branch your-branch-name 8c87714

Random record from MongoDB

Using Python (pymongo), the aggregate function also works.

collection.aggregate([{'$sample': {'size': sample_size }}])

This approach is a lot faster than running a query for a random number (e.g. collection.find([random_int]). This is especially the case for large collections.

How to skip a iteration/loop in while-loop

While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.

Which loop is faster, while or for?

It shouldn't matter which is faster. If it does matter then benchmark it using your real code and see for yourself.

The answers to this other question might be useful as well: How to write more efficient code

More than 1 row in <Input type="textarea" />

The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.

How to view user privileges using windows cmd?

Go to command prompt and enter the command,

net user <username>

Will show your local group memberships.

If you're on a domain, use localgroup instead:

net localgroup Administrators or net localgroup [Admin group name]

Check the list of local groups with localgroup on its own.

net localgroup

Html.EditorFor Set Default Value

This is my working code:

@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @Value = "123" } })

my difference with other answers is using Value inside the htmlAttributes array

How to use basic authorization in PHP curl

Try the following code :

$username='ABC';
$password='XYZ';
$URL='<URL>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

How should I escape strings in JSON?

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

error: (-215) !empty() in function detectMultiScale

The error occurs due to missing of xml files or incorrect path of xml file.

Please try the following code,

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

View HTTP headers in Google Chrome?

I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.

Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.

It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.

https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb

Enjoy!

How can I output a UTF-8 CSV in PHP that Excel will read properly?

I just tried these headers and got Excel 2013 on a Windows 7 PC to import the CSV file with special characters correctly. The Byte Order Mark (BOM) was the final key that made it work.


    header('Content-Encoding: UTF-8');
    header('Content-type: text/csv; charset=UTF-8');
    header("Content-disposition: attachment; filename=filename.csv");
    header("Pragma: public");
    header("Expires: 0");
    echo "\xEF\xBB\xBF"; // UTF-8 BOM

Regex match digits, comma and semicolon?

boolean foundMatch = Pattern.matches("[0-9,;]+", "131;23,87");

Python error: "IndexError: string index out of range"

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

so_far = " " * len(word)

?

Edit:

try something like

print "%d / %d" % (new, so_far)

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

SQL Server: Is it possible to insert into two tables at the same time?

Insert can only operate on one table at a time. Multiple Inserts have to have multiple statements.

I don't know that you need to do the looping through a table variable - can't you just use a mass insert into one table, then the mass insert into the other?

By the way - I am guessing you mean copy the data from Object_Table; otherwise the question does not make sense.

What is the best open XML parser for C++?

Try TinyXML or IrrXML...Both are lightweight XML parsers ( I'd suggest you to use TinyXML, anyway ).

Best way to store time (hh:mm) in a database

DATETIME start DATETIME end

I implore you to use two DATETIME values instead, labelled something like event_start and event_end.

Time is a complex business

Most of the world has now adopted the denery based metric system for most measurements, rightly or wrongly. This is good overall, because at least we can all agree that a g, is a ml, is a cubic cm. At least approximately so. The metric system has many flaws, but at least it's internationally consistently flawed.

With time however, we have; 1000 milliseconds in a second, 60 seconds to a minute, 60 minutes to an hour, 12 hours for each half a day, approximately 30 days per month which vary by the month and even year in question, each country has its time offset from others, the way time is formatted in each country vary.

It's a lot to digest, but the long and short of it is impossible for such a complex scenario to have a simple solution.

Some corners can be cut, but there are those where it is wiser not to

Although the top answer here suggests that you store an integer of minutes past midnight might seem perfectly reasonable, I have learned to avoid doing so the hard way.

The reasons to implement two DATETIME values are for an increase in accuracy, resolution and feedback.

These are all very handy for when the design produces undesirable results.

Am I storing more data than required?

It might initially appear like more information is being stored than I require, but there is a good reason to take this hit.

Storing this extra information almost always ends up saving me time and effort in the long-run, because I inevitably find that when somebody is told how long something took, they'll additionally want to know when and where the event took place too.

It's a huge planet

In the past, I have been guilty of ignoring that there are other countries on this planet aside from my own. It seemed like a good idea at the time, but this has ALWAYS resulted in problems, headaches and wasted time later on down the line. ALWAYS consider all time zones.

C#

A DateTime renders nicely to a string in C#. The ToString(string Format) method is compact and easy to read.

E.g.

new TimeSpan(EventStart.Ticks - EventEnd.Ticks).ToString("h'h 'm'm 's's'")

SQL server

Also if you're reading your database seperate to your application interface, then dateTimes are pleasnat to read at a glance and performing calculations on them are straightforward.

E.g.

SELECT DATEDIFF(MINUTE, event_start, event_end)

ISO8601 date standard

If using SQLite then you don't have this, so instead use a Text field and store it in ISO8601 format eg.

"2013-01-27T12:30:00+0000"

Notes:

  • This uses 24 hour clock*

  • The time offset (or +0000) part of the ISO8601 maps directly to longitude value of a GPS coordiate (not taking into account daylight saving or countrywide).

E.g.

TimeOffset=(±Longitude.24)/360 

...where ± refers to east or west direction.

It is therefore worth considering if it would be worth storing longitude, latitude and altitude along with the data. This will vary in application.

  • ISO8601 is an international format.

  • The wiki is very good for further details at http://en.wikipedia.org/wiki/ISO_8601.

  • The date and time is stored in international time and the offset is recorded depending on where in the world the time was stored.

In my experience there is always a need to store the full date and time, regardless of whether I think there is when I begin the project. ISO8601 is a very good, futureproof way of doing it.

Additional advice for free

It is also worth grouping events together like a chain. E.g. if recording a race, the whole event could be grouped by racer, race_circuit, circuit_checkpoints and circuit_laps.

In my experience, it is also wise to identify who stored the record. Either as a seperate table populated via trigger or as an additional column within the original table.

The more you put in, the more you get out

I completely understand the desire to be as economical with space as possible, but I would rarely do so at the expense of losing information.

A rule of thumb with databases is as the title says, a database can only tell you as much as it has data for, and it can be very costly to go back through historical data, filling in gaps.

The solution is to get it correct first time. This is certainly easier said than done, but you should now have a deeper insight of effective database design and subsequently stand a much improved chance of getting it right the first time.

The better your initial design, the less costly the repairs will be later on.

I only say all this, because if I could go back in time then it is what I'd tell myself when I got there.

Create dataframe from a matrix

I've found the following "cheat" to work very neatly and error-free

> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary

Et voila!

In Python, how do I index a list with another list?

A functional approach:

a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]

from operator import itemgetter

print(list(itemgetter(*b)(a)))
[1, 34, 12]

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

This isn't appropriate in all situations but you can conditionally return false inside the component itself if a certain criteria is or isn't met.

It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.

import React, { Component } from 'react';

export default class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hideComponent: false
        }
    }

    closeThis = () => {
        this.setState(prevState => ({
            hideComponent: !prevState.hideComponent
        })
    });

    render() {
        if (this.state.hideComponent === true) {return false;}

        return (
            <div className={`content`} onClick={() => this.closeThis}>
                YOUR CODE HERE
            </div>
        );
    }
}

How do I check if an index exists on a table field in MySQL?

SHOW KEYS FROM  tablename WHERE Key_name='unique key name'

you can find if there exists an unique key in the table

Server configuration is missing in Eclipse

In Eclipse Neo
1. Window -> Show view -> Servers
2. Right click on server -> choose Properties
3. From General Tab -> Switch Location

Check if table exists

You can use the available meta data:

  DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, "My_Table_Name", 
     new String[] {"TABLE"});
  while (res.next()) {
     System.out.println(
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 
  }

See here for more details. Note also the caveats in the JavaDoc.

Transitions on the CSS display property

I found better way for this issue, you can use CSS Animation and make your awesome effect for showing items.

.item {
     display: none;
}

.item:hover {
     display: block;
     animation: fade_in_show 0.5s
}

@keyframes fade_in_show {
     0% {
          opacity: 0;
          transform: scale(0)
     }

     100% {
          opacity: 1;
          transform: scale(1)
     }
}

How can I get the current user's username in Bash?

An alternative to whoami is id -u -n.

id -u will return the user id (e.g. 0 for root).

403 Forbidden You don't have permission to access /folder-name/ on this server

**403 Forbidden **

You don't have permission to access /Folder-Name/ on this server**

The solution for this problem is:

1.go to etc/apache2/apache2.conf

2.find the below code and change AllowOverride all to AllowOverride none

 <Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride all      Change this to--->  AllowOverride none
    Require all granted
 </Directory>

It will work fine on your Ubuntu server

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

hibernate - get id after save object

The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.

Save() return value:

Serializable save(Object object) throws HibernateException

Returns:

the generated identifier

Getter method example:

UserDetails entity:

@Entity
public class UserDetails {
    @Id
    @GeneratedValue
    private int id;
    private String name;

    // Constructor, Setters & Getters
}

Logic to test the id's :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");

//int userId = (Integer) session.save(user1); // if you want to save the id to some variable

System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());

session.save(user1);
session.save(user2);

System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());

session.getTransaction().commit();

Output of this code:

before save : user id's = 0 , 0

after save : user id's = 1 , 2

As per this output, you can see that the id's were not set before we save the UserDetails entity, once you save the entities then Hibernate set's the id's for your objects - user1 and user2

Name node is in safe mode. Not able to leave

Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:

hadoop dfsadmin -safemode leave

If you are using cloudera manager:

go to >>Actions>>Leave Safemode

But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.

free -m

If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)

C# function to return array

You're trying to return variable Labels of type ArtworkData instead of array, therefore this needs to be in the method signature as its return type. You need to modify your code as such:

public static ArtworkData[] GetDataRecords(int UsersID)
{
    ArtworkData[] Labels;
    Labels = new ArtworkData[3];

    return Labels;
}

Array[] is actually an array of Array, if that makes sense.

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
        <thead>
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            </tr>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>
            </tr>
        </tbody>
    </table>

bootply

Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

        <thead>
            <tr>
                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>
            </tr>
        </thead>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

Rails 3 check if attribute changed

Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:

@user.street1_changed? # => true/false

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

SQL Server Operating system error 5: "5(Access is denied.)"

For me it was solved in the following way with SQL Server Management studio -Log in as admin (I logged in as windows authentication) -Attach the mdf file (right click Database | attach | Add ) -Log out as admin -Log in as normal user

Best way to reset an Oracle sequence to the next value in an existing column?

With oracle 10.2g:

select  level, sequence.NEXTVAL
from  dual 
connect by level <= (select max(pk) from tbl);

will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.

Sort a Map<Key, Value> by values

Instead of using Collections.sort as some do I'd suggest using Arrays.sort. Actually what Collections.sort does is something like this:

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    Object[] a = list.toArray();
    Arrays.sort(a);
    ListIterator<T> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);
    }
}

It just calls toArray on the list and then uses Arrays.sort. This way all the map entries will be copied three times: once from the map to the temporary list (be it a LinkedList or ArrayList), then to the temporary array and finally to the new map.

My solution ommits this one step as it does not create unnecessary LinkedList. Here is the code, generic-friendly and performance-optimal:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) 
{
    @SuppressWarnings("unchecked")
    Map.Entry<K,V>[] array = map.entrySet().toArray(new Map.Entry[map.size()]);

    Arrays.sort(array, new Comparator<Map.Entry<K, V>>() 
    {
        public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) 
        {
            return e1.getValue().compareTo(e2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : array)
        result.put(entry.getKey(), entry.getValue());

    return result;
}

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

Why does NULL = NULL evaluate to false in SQL server

The confusion arises from the level of indirection (abstraction) that comes about from using NULL.

Going back to the "what's under the Christmas tree" analogy, "Unknown" describes the state of knowledge about what is in Box A.

So if you don't know what's in Box A, you say it's "Unknown", but that doesn't mean that "Unknown" is inside the box. Something other than unknown is in the box, possibly some kind of object, or possibly nothing is in the box.

Similarly, if you don't know what's in Box B, you can label your state of knowledge about the contents as being "Unknown".

So here's the kicker: Your state of knowledge about Box A is equal to your state of knowledge about Box B. (Your state of knowledge in both cases is "Unknown" or "I don't know what's in the Box".) But the contents of the boxes may or may not be equal.

Going back to SQL, ideally you should only be able to compare values when you know what they are. Unfortunately, the label that describes a lack of knowledge is stored in the cell itself, so we're tempted to use it as a value. But we should not use that as a value, because it would lead to "the content of Box A equals the content of Box B when we don't know what's in Box A and/or we don't know what's in Box B. (Logically, the implication "if I don't know what's in Box A and if I don't know what's in Box B, then what's in Box A = What's in Box B" is false.)

Yay, Dead Horse.

How to convert a byte array to a hex string in Java?

Adding a utility jar for simple function is not good option. Instead assemble your own utility classes. following is possible faster implementation.

public class ByteHex {

    public static int hexToByte(char ch) {
        if ('0' <= ch && ch <= '9') return ch - '0';
        if ('A' <= ch && ch <= 'F') return ch - 'A' + 10;
        if ('a' <= ch && ch <= 'f') return ch - 'a' + 10;
        return -1;
    }

    private static final String[] byteToHexTable = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
        "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
        "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
        "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
        "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
        "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
        "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
    };

    private static final String[] byteToHexTableLowerCase = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
        "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
        "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
        "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
        "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
        "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
        "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
    };

    public static String byteToHex(byte b){
        return byteToHexTable[b & 0xFF];
    }

    public static String byteToHex(byte[] bytes){
        if(bytes == null) return null;
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTable[b & 0xFF]);
        return sb.toString();
    }

    public static String byteToHex(short[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(short b : bytes) sb.append(byteToHexTable[((byte)b) & 0xFF]);
        return sb.toString();
    }

    public static String byteToHexLowerCase(byte[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTableLowerCase[b & 0xFF]);
        return sb.toString();
    }

    public static byte[] hexToByte(String hexString) {
        if(hexString == null) return null;
        byte[] byteArray = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            byteArray[i / 2] = (byte) (hexToByte(hexString.charAt(i)) * 16 + hexToByte(hexString.charAt(i+1)));
        }
        return byteArray;
    }

    public static byte hexPairToByte(char ch1, char ch2) {
        return (byte) (hexToByte(ch1) * 16 + hexToByte(ch2));
    }


}

How to tell if a connection is dead in python

From the link Jweede posted:

exception socket.timeout:

This exception is raised when a timeout occurs on a socket
which has had timeouts enabled via a prior call to settimeout().
The accompanying value is a string whose value is currently
always “timed out”.

Here are the demo server and client programs for the socket module from the python docs

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

And the client:

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:

Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...

try:
    s.connect((HOST, PORT))
    s.send("Hello, World!")
    ...
except socket.timeout:
    # whatever you need to do when the connection is dropped

python time + timedelta equivalent

You can change time() to now() for it to work

from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)

C - casting int to char and append char to char

int i = 100;
char c = (char)i;

There is no way to append one char to another. But you can create an array of chars and use it.

Why Would I Ever Need to Use C# Nested Classes

A pattern that I particularly like is to combine nested classes with the factory pattern:

public abstract class BankAccount
{
  private BankAccount() {} // prevent third-party subclassing.
  private sealed class SavingsAccount : BankAccount { ... }
  private sealed class ChequingAccount : BankAccount { ... }
  public static BankAccount MakeSavingAccount() { ... }
  public static BankAccount MakeChequingAccount() { ... }
}

By nesting the classes like this, I make it impossible for third parties to create their own subclasses. I have complete control over all the code that runs in any bankaccount object. And all my subclasses can share implementation details via the base class.

What are the rules for casting pointers in C?

char c = '5'

A char (1 byte) is allocated on stack at address 0x12345678.

char *d = &c;

You obtain the address of c and store it in d, so d = 0x12345678.

int *e = (int*)d;

You force the compiler to assume that 0x12345678 points to an int, but an int is not just one byte (sizeof(char) != sizeof(int)). It may be 4 or 8 bytes according to the architecture or even other values.

So when you print the value of the pointer, the integer is considered by taking the first byte (that was c) and other consecutive bytes which are on stack and that are just garbage for your intent.

ActiveXObject is not defined and can't find variable: ActiveXObject

A web app can request access to a sandboxed file system by calling window.requestFileSystem(). Works in Chrome.

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var fs = null;

window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (filesystem) {
    fs = filesystem;
}, errorHandler);

fs.root.getFile('Hello.txt', {
    create: true
}, null, errorHandler);

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

More info here.

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

How to backup MySQL database in PHP?

While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.

I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.

The basic usage of mysqldump is

mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like

mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like

<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.

It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.

You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

Android set height and width of Custom view programmatically

On Kotlin you can set width and height of any view directly using their virtual properties:

someView.layoutParams.width = 100
someView.layoutParams.height = 200

horizontal scrollbar on top and bottom of table

There is one way to achieve this that I did not see anybody mentioning here.

By rotating the parent container by 180 degrees and the child-container again by 180 degrees the scrollbar will be shown at top

.parent {
  transform: rotateX(180deg);
  overflow-x: auto;
} 
.child {
  transform: rotateX(180deg);
}

For reference see the issue in the w3c repository.

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

I found the problem. Instead of adding a class (.cs) file by mistake I had added a Web API Controller class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0). It worked when I removed that file, cleaned the application and then published.

How can I get a uitableViewCell by indexPath?

Finally, I get the cell using the following code:

UITableViewCell *cell = (UITableViewCell *)[(UITableView *)self.view cellForRowAtIndexPath:nowIndex];

Because the class is extended UITableViewController:

@interface SearchHotelViewController : UITableViewController

So, the self is "SearchHotelViewController".

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

UTF-8 all the way through

I have just went through the same issue and found a good solution at PHP manuals.

I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.

if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
   printf("Current character set: %s\n", $mysqli->character_set_name());
}

View Source

click or change event on radio using jquery

_x000D_
_x000D_
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
     console.log(e.type);_x000D_
     return false;_x000D_
});
_x000D_
_x000D_
_x000D_

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

Using multiple IF statements in a batch file

You can structurize your batch file by using goto

IF EXIST somefile.txt goto somefileexists
goto exit

:somefileexists
IF EXIST someotherfile.txt SET var=...

:exit

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04
==============================================================================

Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Tensorflow has a fix in tf-nightly version.

!pip install tf-nightly

The current version is '2.0.0-dev20190511'.

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

Array functions in jQuery

Have a look at https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

How can I calculate an md5 checksum of a directory?

md5sum worked fine for me, but I had issues with sort and sorting file names. So instead I sorted by md5sum result. I also needed to exclude some files in order to create comparable results.

find . -type f -print0 \ | xargs -r0 md5sum \ | grep -v ".env" \ | grep -v "vendor/autoload.php" \ | grep -v "vendor/composer/" \ | sort -d \ | md5sum

What is the best IDE for PHP?

I have a friend who swears by Aptana Studio.

Xcode Objective-C | iOS: delay function / NSTimer help?

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     do something to the button(s)
});

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

How to find the operating system version using JavaScript?

I can't comment on @Ian Ippolito answer (because I would have if I had the rep) but according to the document his comment linked, I'm fairly certain you can find the Chrome version for IOS. https://developer.chrome.com/multidevice/user-agent?hl=ja lists the UA as: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1

So this should work:

if ((verOffset = nAgt.indexOf('CriOS')) != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                version = nAgt.substring(verOffset + 6);//should get the criOS ver.
            }

Haven't been able to test (otherwise I would have improved his answer) it to make sure since my iPad is at home and I'm at work, but I thought I'd put it out there.

How do I read input character-by-character in Java?

If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.

Count number of columns in a table row

If the colspan or rowspan is all set to 1, counting the children tds will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of tds of the rows. Consider the following example:

_x000D_
_x000D_
var mytable = document.getElementById('table')_x000D_
for (var i=0; i < mytable.rows.length; ++i) {_x000D_
 document.write(mytable.rows[i].cells.length + "<br>");_x000D_
}
_x000D_
table, th, td {_x000D_
  border: 1px solid black;_x000D_
  border-collapse: collapse;_x000D_
  padding: 3px;_x000D_
}
_x000D_
<table id="table">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th colspan="2">Header</th>_x000D_
            <th rowspan="2">Hi</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Month</th>_x000D_
            <th>Savings</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td colspan="2">hello</td>_x000D_
            <td>world</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>hello</td>_x000D_
            <td colspan="2">again</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Screen width in React Native

Just discovered react-native-responsive-screen repo here. Found it very handy.

react-native-responsive-screen is a small library that provides 2 simple methods so that React Native developers can code their UI elements fully responsive. No media queries needed.

It also provides an optional third method for screen orienation detection and automatic rerendering according to new dimensions.

Material UI and Grid system

Material UI have implemented their own Flexbox layout via the Grid component.

It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.

You can install it via:

npm install @material-ui/core

It is now in the official documentation with code examples.

did you specify the right host or port? error on Kubernetes

I got this issue when using " Bash on Windows " with azure kubernetes

az aks get-credentials -n <myCluster>-g <myResourceGroup>

The config file is autogenerated and placed in '~/.kube/config' file as per OS (which is windows in my case)

To solve this - Run from Bash commandline cp <yourWindowsPathToConfigPrintedFromAbobeCommand> ~/.kube/config

The system cannot find the file specified. in Visual Studio

The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a # infront of include, you have a stray >> at the end of your cout line and you need std:: infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.

Code which builds and runs:

#include <iostream>

int main()
{
   std::cout << "Hello World";
   system("pause");
   return 0;
}

How to negate specific word in regex?

The following regex will do what you want (as long as negative lookbehinds and lookaheads are supported), matching things properly; the only problem is that it matches individual characters (i.e. each match is a single character rather than all characters between two consecutive "bar"s), possibly resulting in a potential for high overhead if you're working with very long strings.

b(?!ar)|(?<!b)a|a(?!r)|(?<!ba)r|[^bar]

How to smooth a curve in the right way?

If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph

smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()

where timeseries is your set of data passed you can alter windowsize for more smoothining.

"Cross origin requests are only supported for HTTP." error when loading a local file

Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"

npm install http-server -g
http-server [path] [options]

Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.

linux shell script: split string, put them in an array then loop through them

You can probably skip the step of explicitly creating an array...

One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.

Below is an example using semicolons (as you had mentioned in your question):

export IFS=";"
sentence="one;two;three"
for word in $sentence; do
  echo "$word"
done

Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).

How do I grep for all non-ASCII characters?

The following code works:

find /tmp | perl -ne 'print if /[^[:ascii:]]/'

Replace /tmp with the name of the directory you want to search through.

iOS: Convert UTC NSDate to local Timezone

If you want local Date and time. Try this code:-

NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];

Comparing date part only without comparing time in JavaScript

Comparing with setHours() will be a solution. Sample:

var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
    console.log(true)
}else{
    console.log(false)
}

How to call javascript function on page load in asp.net

use your code within

  <script type="text/javascript">
     function window.onload()
       {

        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
       document.getElementById('<%= offSet.ClientID%>').value = retVal;

      }
  </script>

Iterate through object properties

To add ES2015's usage of Reflect.ownKeys(obj) and also iterating over the properties via an iterator.

For example:

let obj = { a: 'Carrot', b: 'Potato', Car: { doors: 4 } };

can be iterated over by

// logs each key
Reflect.ownKeys(obj).forEach(key => console.log(key));

If you would like to iterate directly over the values of the keys of an object, you can define an iterator, just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set.

JS will attempt to iterate via the default iterator property, which must be defined as Symbol.iterator.

If you want to be able to iterate over all objects you can add it as a prototype of Object:

Object.prototype[Symbol.iterator] = function*() { 
    for(p of Reflect.ownKeys(this)){ yield this[p]; }
}

This would enable you to iterate over the values of an object with a for...of loop, for example:

for(val of obj) { console.log('Value is:' + val ) }

Caution: As of writing this answer (June 2018) all other browsers, but IE, support generators and for...of iteration via Symbol.iterator

Mac OS X - EnvironmentError: mysql_config not found

I had been debugging this problem forever - 3 hours 17 mins. What particularly annoyed me was that I already had sql installed on my system through prior uni work but pip/pip3 wasn't recognising it. These threads above and many other I scoured the internet for were helpful in eluminating the problem but didn't actually solve things.

ANSWER

Pip is looking for mysql binaries in the Homebrew Directory which is located relative to Macintosh HD @

/usr/local/Cellar/

so I found that this requires you making a few changes

step 1: Download MySql if not already done so https://dev.mysql.com/downloads/

Step 2: Locate it relative to Macintosh HD and cd

/usr/local/mysql/bin

Step 3: Once there open terminal and use a text editor of choice - I'm a neovim guy myself so I typed (doesn't automatically come with Mac... another story for another day)

nvim mysql_config

Step 4: You will see at approx line 112

# Create options 
libs="-L$pkglibdir"
libs="$libs -l "

Change to

# Create options 
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

*you'll notice that this file has read-only access so if your using vim or neovim

:w !sudo tee %

Step 5: Head to the home directory and edit the .bash_profile file

cd ~

Then

nvim .bash_profile

and add

export PATH="/usr/local/mysql/bin:$PATH"

to the file then save

Step 6: relative to Macintosh HD locate paths and add to it

cd /private/etc/

then

nvim paths

and add

/usr/local/mysql/bin

*you'll again notice that this file has read-only access so if your using vim or neovim

:w !sudo tee % 

then

cd ~

then refresh the terminal with your changes by running

source .bash_profile

Finally

pip3 install mysqlclient

And Viola. Remember it's a vibe.

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

How to read a large file line by line?

Need to frequently read a large file from last position reading ?

I have created a script used to cut an Apache access.log file several times a day. So I needed to set a position cursor on last line parsed during last execution. To this end, I used file.seek() and file.seek() methods which allows the storage of the cursor in file.

My code :

ENCODING = "utf8"
CURRENT_FILE_DIR = os.path.dirname(os.path.abspath(__file__))

# This file is used to store the last cursor position
cursor_position = os.path.join(CURRENT_FILE_DIR, "access_cursor_position.log")

# Log file with new lines
log_file_to_cut = os.path.join(CURRENT_FILE_DIR, "access.log")
cut_file = os.path.join(CURRENT_FILE_DIR, "cut_access", "cut.log")

# Set in from_line 
from_position = 0
try:
    with open(cursor_position, "r", encoding=ENCODING) as f:
        from_position = int(f.read())
except Exception as e:
    pass

# We read log_file_to_cut to put new lines in cut_file
with open(log_file_to_cut, "r", encoding=ENCODING) as f:
    with open(cut_file, "w", encoding=ENCODING) as fw:
        # We set cursor to the last position used (during last run of script)
        f.seek(from_position)
        for line in f:
            fw.write("%s" % (line))

    # We save the last position of cursor for next usage
    with open(cursor_position, "w", encoding=ENCODING) as fw:
        fw.write(str(f.tell()))

How to remove td border with html?

To remove borders between cells, while retaining the border around the table, add the attribute rules=none to the table tag.

There is no way in HTML to achieve the rendering specified in the last figure of the question. There are various tricky workarounds that are based on using some other markup structure.

How do I replace all the spaces with %20 in C#?

HttpServerUtility.HtmlEncode

From the documentation:

String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);

But this actually encodes HTML, not URLs. Instead use UrlEncode(TestString).

npm install -g less does not work: EACCES: permission denied

Another option is to download and install a new version using an installer.

https://nodejs.org/en/download/

How to make circular background using css?

Here is a solution for doing it with a single div element with CSS properties, border-radius does the magic.

CSS:

.circle{
    width:100px;
    height:100px;
    border-radius:50px;
    font-size:20px;
    color:#fff;
    line-height:100px;
    text-align:center;
    background:#000
}

HTML:

<div class="circle">Hello</div>

Dialog with transparent background in Android

Set these style code in style

<style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</style>

And simply change false to true below line

<item name="android:backgroundDimEnabled">true</item>

It will dim your background.

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Hide the browse button on a input type=file

HTML - InputFile component can be hide by writing some css. Here I am adding an icon which overrides inputfile component.

<label class="custom-file-upload">
    <InputFile OnChange="HandleFileSelected" />
    <i class="fa fa-cloud-upload"></i> Upload
</label>

css-

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        border: 1px solid #ccc;
        display: inline-block;
        padding: 6px 12px;
        cursor: pointer;
    }
</style>

Backup/Restore a dockerized PostgreSQL database

dksnap (https://github.com/kelda/dksnap) automates the process of running pg_dumpall and loading the dump via /docker-entrypoint-initdb.d.

It shows you a list of running containers, and you pick which one you want to backup. The resulting artifact is a regular Docker image, so you can then docker run it, or share it by pushing it to a Docker registry.

(disclaimer: I'm a maintainer on the project)

iPad Multitasking support requires these orientations

As Michael said check the "Requires Full Screen" checkbox under General > Targets

and also delete the 'CFBundleIcons-ipad' from the info.plst

This worked for me

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

Save results to csv file with Python

You can save it as follow if you have Pandas Dataframe

   df.to_csv(r'/dir/filename.csv')

How to check if any flags of a flag combination are set?

If you can use .NET 4 or higher than use HasFlag() method

examples

letter.HasFlag(Letters.A | Letters.B) // both A and B must be set

same as

letter.HasFlag(Letters.AB)

SSH configuration: override the default username

If you only want to ssh a few times, such as on a borrowed or shared computer, try:

ssh buck@hostname

or

ssh -l buck hostname

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

add onclick function to a submit button

  1. Create a hidden button with id="hiddenBtn" and type="submit" that do the submit
  2. Change current button to type="button"
  3. set onclick of the current button call a function look like below:

    function foo() { // do something before submit ... // trigger click event of the hidden button $('#hinddenBtn').trigger("click"); }

Undefined reference to sqrt (or other mathematical functions)

I suppose you have imported math.h with #include <math.h>

So the only other reason I can see is a missing linking information. You must link your code with the -lm option.

If you're simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some informations about your building process.

Create XML file using java

You can use Xembly, a small open source library that makes this XML creating process much more intuitive:

String xml = new Xembler(
  new Directives()
    .add("root")
    .add("order")
    .attr("id", "553")
    .set("$140.00")
).xml();

Xembly is a wrapper around native Java DOM, and is a very lightweight library.

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

TL;DR

The object returned by range() is actually a range object. This object implements the iterator interface so you can iterate over its values sequentially, just like a generator, list, or tuple.

But it also implements the __contains__ interface which is actually what gets called when an object appears on the right hand side of the in operator. The __contains__() method returns a bool of whether or not the item on the left-hand-side of the in is in the object. Since range objects know their bounds and stride, this is very easy to implement in O(1).

Python try-else

Suppose your programming logic depends on whether a dictionary has an entry with a given key. You can test the result of dict.get(key) using if... else... construct, or you can do:

try:
    val = dic[key]
except KeyError:
    do_some_stuff()
else:
    do_some_stuff_with_val(val)

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

How to get the filename without the extension from a path in Python?

For convenience, a simple function wrapping the two methods from os.path :

def filename(path):
  """Return file name without extension from path.

  See https://docs.python.org/3/library/os.path.html
  """
  import os.path
  b = os.path.split(path)[1]  # path, *filename*
  f = os.path.splitext(b)[0]  # *file*, ext
  #print(path, b, f)
  return f

Tested with Python 3.5.

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

UITapGestureRecognizer - single tap and double tap

In reference to @stanley's comment -

Don't try and use tap gestures to row selections to work in UITableView as it already has full tap handling....

But you must set 'Cancels Touches in View' to 'NO' on your single tap gesture recognizers or it will never get the tap events.

SQL statement to get column type

use this query

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TABLE_NAME'
ORDER BY ORDINAL_POSITION

Google Maps API v3: How to remove all markers?

I know that this maybe a simiple solution, but this is what I do

$("#map_canvas").html("");
markers = [];

Works every time for me.

How do I see active SQL Server connections?

You can perform the following T-SQL command:

SELECT * FROM sys.dm_exec_sessions WHERE status = 'running';

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

I had to install MariaDB. I am using OpenSUSE LINUX Leap 15 and had to execute these commands:

sudo zypper update
sudo zypper install mariadb mariadb-client mariadb-tools
sudo systemctl start mysql
sudo systemctl enable mysql //enable auto start at boot time3
sudo mysql_secure_installation

Source.

Get connection status on Socket.io client

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

how to configure lombok in eclipse luna

While installing lombok in ubuntu machine with java -jar lombok.jar you may find following error:

java.awt.AWTError: Assistive Technology not found: org.GNOME.Accessibility.AtkWrapper

You can overcome this by simply doing following steps:

Step 1: This can be done by editing the accessibility.properties file of JDK:

sudo gedit /etc/java-8-openjdk/accessibility.properties

Step 2: Comment (#) the following line:

assistive_technologies=org.GNOME.Accessibility.AtkWrapper

Multi-character constant warnings

Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

int x = *(int*)"abcd";

Or a bit more specific:

int x = *(int32_t*)"abcd";

One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

int x = ((union {char s[5]; int number;}){"abcd"}).number;

/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");

Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When we create a new RDS DB instance, the default master user is not the root user. But only gets certain privileges for that DB instance. This permission does not include SET permission. Now if your default master user tries to execute mysql SET commands, then you will face this error: Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation

Solution 1

Comment out or remove these lines

SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;
SET @@SESSION.SQL_LOG_BIN= 1;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';

Solution 2

You can also ignore the errors by using the -f option to load the rest of the dump file.

mysql -f <REPLACE_DB_NAME> -u <REPLACE_DB_USER> -h <DB_HOST_HERE> -p < dumpfile.sql

how to configuring a xampp web server for different root directory

You can change the port while you open your XAMP control panel, follow the steps:

  1. click on config net to the start button, and
  2. select httpd.conf, a text file will open
  3. check the file and file listen:80,
  4. once got listen:80 replace with listen:8080 and
  5. save in the same folder.

Once done that, you will be able to start your local server.

AttributeError: 'module' object has no attribute

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.

How to find out if a Python object is a string?

Python 2

Use isinstance(obj, basestring) for an object-to-test obj.

Docs.

Convert String into a Class Object

As stated by others, your question is ambiguous at best. The problem is, you want to represent the object as a string, and then be able to construct the object again from that string.

However, note that while many object types in Java have string representations, this does not guarantee that an object can be constructed from its string representation.

To quote this source,

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time.

So, you see, what you want might not be possible. But it is possible to save your object's state to a byte sequence, and then reconstruct it from that byte sequence.

Linux cmd to search for a class file among jars irrespective of jar path

Linux, Walkthrough to find a class file among many jars.

Go to the directory that contains the jars underneath.

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ ls
blah.txt                             metrics-core-2.2.0.jar
jopt-simple-3.2.jar                  scala-library-2.10.1.jar
kafka_2.10-0.8.1.1-sources.jar       zkclient-0.3.jar
kafka_2.10-0.8.1.1-sources.jar.asc   zookeeper-3.3.4.jar
log4j-1.2.15.jar

I'm looking for which jar provides for the Producer class.

Understand how the for loop works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `seq 1 3`; do
> echo $i
> done
1
2
3

Understand why find this works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ find . -name "*.jar"
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./slf4j-1.7.7/osgi-over-slf4j-1.7.7-sources.jar

You can pump all the jars underneath into the for loop:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done

./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar

Now we can operate on each one:

Do a jar tf on every jar and cram it into blah.txt:

for i in `find . -name "*.jar"`; do echo $i; jar tf $i; done > blah.txt

Inspect blah.txt, it's a list of all the classes in all the jars. You can search that file for the class you want, then look for the jar that came before it, that's the one you want.

What's the best way to convert a number to a string in JavaScript?

The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x). Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".

Explanation:

String(x) handles nulls, undefined, Symbols, [anything] and calls .toString() for objects.

'' + x calls .valueOf() on x (casting to number), throws on Symbols, can provide implementation dependent results.

x.toString() throws on nulls and undefined.

Note: String(x) will still fail on prototype-less objects like Object.create(null).

If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:

/**
 * Safely casts any value to string. Null and undefined are converted to ''.
 * @param  {*} value
 * @return {string}
 */
function string (str) {
  return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}

Initial bytes incorrect after Java AES/CBC decryption

It's often the good idea to rely on standard library provided solution:

private static void stackOverflow15554296()
    throws
        NoSuchAlgorithmException, NoSuchPaddingException,        
        InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException
{

    // prepare key
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecretKey aesKey = keygen.generateKey();
    String aesKeyForFutureUse = Base64.getEncoder().encodeToString(
            aesKey.getEncoded()
    );

    // cipher engine
    Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

    // cipher input
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] clearTextBuff = "Text to encode".getBytes();
    byte[] cipherTextBuff = aesCipher.doFinal(clearTextBuff);

    // recreate key
    byte[] aesKeyBuff = Base64.getDecoder().decode(aesKeyForFutureUse);
    SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");

    // decipher input
    aesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
    byte[] decipheredBuff = aesCipher.doFinal(cipherTextBuff);
    System.out.println(new String(decipheredBuff));
}

This prints "Text to encode".

Solution is based on Java Cryptography Architecture Reference Guide and https://stackoverflow.com/a/20591539/146745 answer.

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

Eclipse error ... cannot be resolved to a type

I just closed all the files and reopened them, and voila!!! Hope this helps someone in the future ;)

Confirm deletion using Bootstrap 3 modal box

$('.launchConfirm').on('click', function (e) {
    $('#confirm')
        .modal({ backdrop: 'static', keyboard: false })
        .one('click', '#delete', function (e) {
            //delete function
        });
});

FIDDLE

For your button:

<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>

Transport endpoint is not connected

This typically is caused by the mount directory being left mounted due to a crash of your filesystem. Go to the parent directory of the mount point and enter fusermount -u YOUR_MNT_DIR.

If this doesn't do the trick, do sudo umount -l YOUR_MNT_DIR.

Java stack overflow error - how to increase the stack size in Eclipse?

When the argument -Xss doesn't do the job try deleting the temporary files from:

c:\Users\{user}\AppData\Local\Temp\.

This did the trick for me.

How to send control+c from a bash script?

Ctrl+C sends a SIGINT signal.

kill -INT <pid> sends a SIGINT signal too:

# Terminates the program (like Ctrl+C)
kill -INT 888
# Force kill
kill -9 888

Assuming 888 is your process ID.


Note that kill 888 sends a SIGTERM signal, which is slightly different, but will also ask for the program to stop. So if you know what you are doing (no handler bound to SIGINT in the program), a simple kill is enough.

To get the PID of the last command launched in your script, use $! :

# Launch script in background
./my_script.sh &
# Get its PID
PID=$!
# Wait for 2 seconds
sleep 2
# Kill it
kill $PID

Operation must use an updatable query. (Error 3073) Microsoft Access

I kept getting the same error until I made the connecting field a unique index in both connecting tables. Only then did the query become updatable.

Philip Stilianos

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

How can you create multiple cursors in Visual Studio Code

Try Ctrl+Alt+Shift+? / ?, without mouse, or hold "alt" and click on all the lines you want.

Note: Tested on Windows.

View tabular file such as CSV from command line

I wrote a script, viewtab , in Groovy for just this purpose. You invoke it like:

viewtab filename.csv

It is basically a super-lightweight spreadsheet that can be invoked from the command line, handles CSV and tab separated files, can read VERY large files that Excel and Numbers choke on, and is very fast. It's not command-line in the sense of being text-only, but it is platform independent and will probably fit the bill for many people looking for a solution to the problem of quickly inspecting many or large CSV files while working in a command line environment.

The script and how to install it are described here:

http://bayesianconspiracy.blogspot.com/2012/06/quick-csvtab-file-viewer.html

How can I enable Assembly binding logging?

  1. Create a new Application Pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new Pool

Screenshot (IIS-ApplicationPool)

Set UILabel line spacing

Best thing I found is: https://github.com/mattt/TTTAttributedLabel

It's a UILabel subclass so you can just drop it in, and then to change the line height:

myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;

Frontend tool to manage H2 database

I haven't used it, but RazorSQL looks pretty good.

Fatal error: Call to undefined function mb_strlen()

PHP 7.2 Ubuntu 18.04

sudo apt install php-mbstring

How to access the contents of a vector from a pointer to the vector in C++?

There are many solutions, here's a few I've come up with:

int main(int nArgs, char ** vArgs)
{
    vector<int> *v = new vector<int>(10);
    v->at(2); //Retrieve using pointer to member
    v->operator[](2); //Retrieve using pointer to operator member
    v->size(); //Retrieve size
    vector<int> &vr = *v; //Create a reference
    vr[2]; //Normal access through reference
    delete &vr; //Delete the reference. You could do the same with
                //a pointer (but not both!)
}

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

Efficiently finding the last line in a text file

#!/usr/bin/python

count = 0

f = open('last_line1','r')

for line in f.readlines():

    line = line.strip()

    count = count + 1

    print line

print count

f.close()

count1 = 0

h = open('last_line1','r')

for line in h.readlines():

    line = line.strip()

    count1 = count1 + 1

    if count1 == count:

       print line         #-------------------- this is the last line

h.close()

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

If reconnecting the WiFi doesn't work for you, try reboot your device.

This works for me. Hope it helps.

Laravel Unknown Column 'updated_at'

For those who are using laravel 5 or above must use public modifier other wise it will throw an exception

Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)

public $timestamps = false;

Properly close mongoose's connection once you're done

Probably you have this:

const db = mongoose.connect('mongodb://localhost:27017/db');

// Do some stuff

db.disconnect();

but you can also have something like this:

mongoose.connect('mongodb://localhost:27017/db');

const model = mongoose.model('Model', ModelSchema);

model.find().then(doc => {
  console.log(doc);
}

you cannot call db.disconnect() but you can close the connection after you use it.

model.find().then(doc => {
  console.log(doc);
}).then(() => {
  mongoose.connection.close();
});

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Flask-SQLAlchemy how to delete all rows in a single table

DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:

num_rows_deleted = db.session.query(Model).delete()

Also, don't forget that the deletion won't take effect until you commit, as in this snippet:

try:
    num_rows_deleted = db.session.query(Model).delete()
    db.session.commit()
except:
    db.session.rollback()

How do I get only directories using Get-ChildItem?

To answer the original question specifically (using IO.FileAttributes):

Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -and [IO.FileAttributes]::Directory}

I do prefer Marek's solution though (Where-Object { $_ -is [System.IO.DirectoryInfo] }).

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

Passing HTML to template using Flask/Jinja2

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don't have to |safe it.

Global variables in Java

Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;
    }

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;
    }
}

In C/C++ what's the simplest way to reverse the order of bits in a byte?

Assuming that your compiler allows unsigned long long:

unsigned char reverse(unsigned char b) {
  return (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
}

Discovered here

How to declare std::unique_ptr and what is the use of it?

There is no difference in working in both the concepts of assignment to unique_ptr.

int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);

is similar to

unique_ptr<int> uptr (new int(3));

Here unique_ptr automatically deletes the space occupied by uptr.


how pointers, declared in this way will be different from the pointers declared in a "normal" way.

If you create an integer in heap space (using new keyword or malloc), then you will have to clear that memory on your own (using delete or free respectively).

In the below code,

int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;

Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.

In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope. So, you need not do delete or free for unique_ptr.

Running Python in PowerShell?

The command [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User") is not a Python command. Instead, this is an operating system command to the set the PATH variable.

You are getting this error as you are inside the Python interpreter which was triggered by the command python you have entered in the terminal (Windows PowerShell).

Please note the >>> at the left side of the line. It states that you are on inside Python interpreter.

Please enter quit() to exit the Python interpreter and then type the command. It should work!

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

How to hide soft keyboard on android after clicking outside EditText?

I liked the approach of calling dispatchTouchEvent made by htafoya, but:

  • I didn't understand the timer part (don't know why measuring the downtime should be necessary?)
  • I don't like to register/unregister all EditTexts with every view-change (could be quite a lot of viewchanges and edittexts in complex hierarchies)

So, I made this somewhat easier solution:

@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
    // all touch events close the keyboard before they are processed except EditText instances.
    // if focus is an EditText we need to check, if the touchevent was inside the focus editTexts
    final View currentFocus = getCurrentFocus();
    if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    return super.dispatchTouchEvent(ev);
}

/**
 * determine if the given motionevent is inside the given view.
 * 
 * @param ev
 *            the given view
 * @param currentFocus
 *            the motion event.
 * @return if the given motionevent is inside the given view
 */
private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
    final int[] loc = new int[2];
    currentFocus.getLocationOnScreen(loc);
    return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0] + currentFocus.getWidth())
        && ev.getRawY() < (loc[1] + currentFocus.getHeight());
}

There is one disadvantage:

Switching from one EditText to another EditText makes the keyboard hide and reshow - in my case it's desired that way, because it shows that you switched between two input components.

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

Jackson - Deserialize using generic class

From Jackson 2.5, an elegant way to solve that is using the TypeFactory.constructParametricType(Class parametrized, Class... parameterClasses) method that allows to define straigthly a Jackson JavaType by specifying the parameterized class and its parameterized types.

Supposing you want to deserialize to Data<String>, you can do :

// the json variable may be a String, an InputStream and so for...
JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, String.class);
Data<String> data = mapper.readValue(json, type);

Note that if the class declared multiple parameterized types, it would not be really harder :

class Data <T, U> {
    int found;
    Class<T> hits;
    List<U> list;
}

We could do :

JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, String.class, Integer);
Data<String, Integer> data = mapper.readValue(json, type);

How to execute a stored procedure inside a select query

"Not Possible". You can do this using this query. Initialize here

declare @sql nvarchar(4000)=''

Set Value & exec command of your sp with parameters

SET @sql += ' Exec spName @param'
EXECUTE sp_executesql @sql,  N'@param type', @param = @param

How to use responsive background image in css3 in bootstrap

Check this out,

body {
    background-color: black;
    background: url(img/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Why does javascript map function return undefined?

var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

How to send data in request body with a GET when using jQuery $.ajax()

Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

_x000D_
_x000D_
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
  if (err) throw new Error(err);_x000D_
  console.log(res);_x000D_
});
_x000D_
_x000D_
_x000D_

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

How to play YouTube video in my Android application?

you can use this project to play any you tube video , in your android app . Now for other video , or Video id ... you can do this https://gdata.youtube.com/feeds/api/users/eminemvevo/uploads/ where eminemvevo = channel .

after finding , video id , you can put that id in cueVideo("video_id")

src -> com -> examples -> youtubeapidemo -> PlayerViewDemoActivity

  @Override
  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player , boolean wasRestored) {
    if (!wasRestored) {
      player.cueVideo("wKJ9KzGQq0w");
    }
  }

And specially for reading that video_id in a better way open this , and it as a xml[1st_file] file in your desktop after it create a new Xml file in your project or upload that[1st_file] saved file in your project , and right_click in it , and open it with xml_editor file , here you will find the video id of the particular video .

enter image description here

How can I convert the "arguments" object to an array in JavaScript?

I recommend using ECMAScript 6 spread operator, which will Bind trailing parameters to an array. With this solution you don't need to touch the arguments object and your code will be simplified. The downside of this solution is that it does not work across most browsers, so instead you will have to use a JS compiler such as Babel. Under the hood Babel transforms arguments into a Array with a for loop.

function sortArgs(...args) {
  return args.sort();
}

If you can not use a ECMAScript 6, I recommend looking at some of the other answers such as @Jonathan Fingland

function sortArgs() {
    var args = Array.prototype.slice.call(arguments);
    return args.sort();
}

org.hibernate.MappingException: Unknown entity: annotations.Users

If your entity is mapped through annotations, add the following code to your configuration;

configuration.addAnnotatedClass(theEntityPackage.EntityClassName.class);

For example;

configuration.addAnnotatedClass(com.foo.foo1.Products.class);

if your entity is mapped with xml file, use addClass instead of addAnnotatedClass.

As an example;

configuration.addClass(com.foo.foo1.Products.class);

Ping me if you need more help.