Programs & Examples On #Credentials

Credentials in information systems are widely used to control access to information or other resources. The classic combination of a user account number or name and a secret password is a widely-used example of IT credentials.

How to save username and password in Git?

You can use the git config to enable credentials storage in git.

git config --global credential.helper store

When running this command, the first time you pull or push from the remote repository, you'll get asked about the username and password.

Afterwards, for consequent communications with the remote repository you don't have to provide the username and password.

The storage format is a .git-credentials file, stored in plaintext.

Also, you can use other helpers for the git config credential.helper, namely memory cache:

git config credential.helper cache <timeout>

which takes an optional timeout parameter, determining for how long the credentials will be kept in memory. Using the helper, the credentials will never touch the disk and will be erased after the specified timeout. The default value is 900 seconds (15 minutes).


WARNING : If you use this method, your git account passwords will be saved in plaintext format, in the global .gitconfig file, e.g in linux it will be /home/[username]/.gitconfig

If this is undesirable to you, use an ssh key for your accounts instead.

SVN change username

Also, for those who happened to realize too late, that they committed with the wrong credentials, the solution (after the fact) is to change the svn author of that revision: see this question

Basically the syntax is:

svn propset --revprop -r (revision_number) svn:author (new username)

Remove credentials from Git

  1. Go to C:\Users\<current-user>
  2. check for .git-credentials file
  3. Delete content or modify as per your requirement
  4. Restart your terminal

git clone: Authentication failed for <URL>

After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:

cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe

Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html

My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.

Using cURL with a username and password?

Usually CURL command refer to as

curl https://example.com\?param\=ParamValue -u USERNAME:PASSWORD

if you don't have any password or want to skip command prompt to demand for password simple leave the password section blank.

i.e. curl https://example.com\?param\=ParamValue -u USERNAME:

AWS : The config profile (MyName) could not be found

Make sure you are in the correct VirtualEnvironment. I updated PyCharm and for some reason had to point my project at my VE again. Opening the terminal, I was not in my VE when attempting zappa update (and got this error). Restarting PyCharm, all back to normal.

HttpWebRequest using Basic authentication

Following code will solve json response if there Basic Authentication and Proxy implemented.Also IIS 7.5 Hosting Problm will resolve.

public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
    string authInfo = username + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//For Proxy
    WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.Accept = "application/json; charset=utf-8";
    request.Proxy = proxy;

    request.Headers["Authorization"] = "Basic " + authInfo;

    var response = (HttpWebResponse)request.GetResponse();

    string strResponse = "";
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        strResponse= sr.ReadToEnd();

    }

    return strResponse;
}

How do I find my host and username on mysql?

The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html

If MySql is running on the same computer as your webserver, you can just use "localhost" as the host

What is the most appropriate way to store user settings in Android application

As others already pointed out you can use SharedPreferences generally but if you would like to store data encrypted it's a bit inconvenient. Fortunately, there is an easier and quicker way to encrypt data now since there is an implementation of SharedPreferences that encrypts keys and values. You can use EncryptedSharedPreferences in Android JetPack Security.

Just add AndroidX Security into your build.gradle:

implementation 'androidx.security:security-crypto:1.0.0-rc01'

And you can use it like this:

String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);

SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
    "secret_shared_prefs",
    masterKeyAlias,
    context,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);

// use the shared preferences and editor as you normally would
SharedPreferences.Editor editor = sharedPreferences.edit();

See more details: https://android-developers.googleblog.com/2020/02/data-encryption-on-android-with-jetpack.html

Official docs: https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences

How to Specify Eclipse Proxy Authentication Credentials?

Here is the workaround:

In eclipse.ini write the following:

-vmargs
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors= org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=*myproxyhost*
-Dhttp.proxyPort=*myproxyport*
-Dhttp.proxyUser=*proxy username*
-Dhttp.proxyPassword=*proxy password*
-Dhttp.nonProxyHosts=localhost|127.0.0.1

After starting eclipse verify, that you use the Manual proxy method.

HTH

Android: Storing username and password?

The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.

I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

Configuring user and password with Git Bash

If the git bash is not working properly due to recently changed password.

You could open the Git GUI, and clone from there. It will ask for password, once entered, you can close the GIT GUI window.

Now the git bash will work perfectly.

Combining "LIKE" and "IN" for SQL Server

Effectively, the IN statement creates a series of OR statements... so

SELECT * FROM table WHERE column IN (1, 2, 3)

Is effectively

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3

And sadly, that is the route you'll have to take with your LIKE statements

SELECT * FROM table
WHERE column LIKE 'Text%' OR column LIKE 'Hello%' OR column LIKE 'That%'

Digital Certificate: How to import .cer file in to .truststore file using?

The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.

You do not have to put an alias and the password of the keystore, you can just type:

keytool -v -import -file somefile.crt  -alias somecrt -keystore my-cacerts

Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.

Update regarding the differences of cer and crt (just to clarify) According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider

CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.

What is the difference between float and double?

Unlike an int (whole number), a float have a decimal point, and so can a double. But the difference between the two is that a double is twice as detailed as a float, meaning that it can have double the amount of numbers after the decimal point.

prevent iphone default keyboard when focusing an <input>

Best way to solve this as per my opinion is Using "ignoreReadonly".

First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.

$('#txtStartDate').datetimepicker({
            locale: "da",
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
        $('#txtEndDate').datetimepicker({
            locale: "da",
            useCurrent: false,
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
});

Passing a 2D array to a C++ function

Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -

void myFunction(double (*myArray) [10]);

I would prefer std::vector over raw arrays.

Using Html.ActionLink to call action on different controller

this code worked for me in partial view:

<a href="/Content/[email protected]">@item.Title</a>

Is there a way to check if a file is in use?

The accepted answers above suffer an issue where if file has been opened for writing with a FileShare.Read mode or if the file has a Read-Only attribute the code will not work. This modified solution works most reliably, with two things to keep in mind (as true for the accepted solution also):

  1. It will not work for files that has been opened with a write share mode
  2. This does not take into account threading issues so you will need to lock it down or handle threading issues separately.

Keeping the above in mind, this checks if the file is either locked for writing or locked to prevent reading:

public static bool FileLocked(string FileName)
{
    FileStream fs = null;

    try
    {
        // NOTE: This doesn't handle situations where file is opened for writing by another process but put into write shared mode, it will not throw an exception and won't show it as write locked
        fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None); // If we can't open file for reading and writing then it's locked by another process for writing
    }
    catch (UnauthorizedAccessException) // https://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx
    {
        // This is because the file is Read-Only and we tried to open in ReadWrite mode, now try to open in Read only mode
        try
        {
            fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (Exception)
        {
            return true; // This file has been locked, we can't even open it to read
        }
    }
    catch (Exception)
    {
        return true; // This file has been locked
    }
    finally
    {
        if (fs != null)
            fs.Close();
    }
    return false;
}

How do I delete all the duplicate records in a MySQL table without temp tables

If you are not using any primary key, then execute following queries at one single stroke. By replacing values:

# table_name - Your Table Name
# column_name_of_duplicates - Name of column where duplicate entries are found

create table table_name_temp like table_name;
insert into table_name_temp select distinct(column_name_of_duplicates),value,type from table_name group by column_name_of_duplicates;
delete from table_name;
insert into table_name select * from table_name_temp;
drop table table_name_temp
  1. create temporary table and store distinct(non duplicate) values
  2. make empty original table
  3. insert values to original table from temp table
  4. delete temp table

It is always advisable to take backup of database before you play with it.

How can I delete one element from an array by value

I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

arr = [1,3,2,44,5]
arr.delete_at(arr.index(44))

#=> [1,3,2,5]

There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Import a module from a relative path

import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

How do I create HTML table using jQuery dynamically?

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

Can I have H2 autocreate a schema in an in-memory database?

What Thomas has written is correct, in addition to that, if you want to initialize multiple schemas you can use the following. Note there is a \\; separating the two create statements.

    EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
                    .setType(EmbeddedDatabaseType.H2)
                    .setName("testDb;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=create " +
                            "schema if not exists " +
                            "schema_a\\;create schema if not exists schema_b;" +
                            "DB_CLOSE_DELAY=-1;")
                    .addScript("sql/provPlan/createTable.sql")
                    .addScript("sql/provPlan/insertData.sql")
                    .addScript("sql/provPlan/insertSpecRel.sql")
                    .build();

ref : http://www.h2database.com/html/features.html#execute_sql_on_connection

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)

Java POI : How to read Excel cell value and not the formula computing it?

For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

 for(Cell cell : row) {
     if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        System.out.println("Formula is " + cell.getCellFormula());
        switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
        }
     }
 }

npm install errors with Error: ENOENT, chmod

In Windows I had a similar error. Search paste App Data and search for the string npm.

I replaced the string 'npm' (including quotes) with 'npm.cmd' in both atlasboard\lib\package-dependency-manager.js and atlasboard\lib\cli\commands.js. That fixed the problem.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified. This makes it seem as if the array is passed by value when in actual fact it isn't.

For example, in this first case, even though you aren't defining your function to accept $my_array by reference (by using the & character in the parameter definition), it still gets passed by reference (ie: you don't waste memory with an unnecessary copy).

function handle_array($my_array) {  

    // ... read from but do not modify $my_array
    print_r($my_array);

    // ... $my_array effectively passed by reference since no copy is made
}

However if you modify the array, a copy of it is made first (which uses more memory but leaves your original array unaffected).

function handle_array($my_array) {

    // ... modify $my_array
    $my_array[] = "New value";

    // ... $my_array effectively passed by value since requires local copy
}

FYI - this is known as "lazy copy" or "copy-on-write".

How to determine total number of open/active connections in ms sql server 2005

SELECT
[DATABASE] = DB_NAME(DBID), 
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME

Go: panic: runtime error: invalid memory address or nil pointer dereference

for me one solution for this problem was to add in sql.Open ... sslmode=disable

In what cases do I use malloc and/or new?

Dynamic allocation is only required when the life-time of the object should be different than the scope it gets created in (This holds as well for making the scope smaller as larger) and you have a specific reason where storing it by value doesn't work.

For example:

 std::vector<int> *createVector(); // Bad
 std::vector<int> createVector();  // Good

 auto v = new std::vector<int>(); // Bad
 auto result = calculate(/*optional output = */ v);
 auto v = std::vector<int>(); // Good
 auto result = calculate(/*optional output = */ &v);

From C++11 on, we have std::unique_ptr for dealing with allocated memory, which contains the ownership of the allocated memory. std::shared_ptr was created for when you have to share ownership. (you'll need this less than you would expect in a good program)

Creating an instance becomes really easy:

auto instance = std::make_unique<Class>(/*args*/); // C++14
auto instance = std::make_unique<Class>(new Class(/*args*/)); // C++11
auto instance = std::make_unique<Class[]>(42); // C++14
auto instance = std::make_unique<Class[]>(new Class[](42)); // C++11

C++17 also adds std::optional which can prevent you from requiring memory allocations

auto optInstance = std::optional<Class>{};
if (condition)
    optInstance = Class{};

As soon as 'instance' goes out of scope, the memory gets cleaned up. Transferring ownership is also easy:

 auto vector = std::vector<std::unique_ptr<Interface>>{};
 auto instance = std::make_unique<Class>();
 vector.push_back(std::move(instance)); // std::move -> transfer (most of the time)

So when do you still need new? Almost never from C++11 on. Most of the you use std::make_unique until you get to a point where you hit an API that transfers ownership via raw pointers.

 auto instance = std::make_unique<Class>();
 legacyFunction(instance.release()); // Ownership being transferred

 auto instance = std::unique_ptr<Class>{legacyFunction()}; // Ownership being captured in unique_ptr

In C++98/03, you have to do manual memory management. If you are in this case, try upgrading to a more recent version of the standard. If you are stuck:

 auto instance = new Class(); // Allocate memory
 delete instance;             // Deallocate
 auto instances = new Class[42](); // Allocate memory
 delete[] instances;               // Deallocate

Make sure that you track the ownership correctly to not have any memory leaks! Move semantics don't work yet either.

So, when do we need malloc in C++? The only valid reason would be to allocate memory and initialize it later via placement new.

 auto instanceBlob = std::malloc(sizeof(Class)); // Allocate memory
 auto instance = new(instanceBlob)Class{}; // Initialize via constructor
 instance.~Class(); // Destroy via destructor
 std::free(instanceBlob); // Deallocate the memory

Even though, the above is valid, this can be done via a new-operator as well. std::vector is a good example for this.

Finally, we still have the elephant in the room: C. If you have to work with a C-library where memory gets allocated in the C++ code and freed in the C code (or the other way around), you are forced to use malloc/free.

If you are in this case, forget about virtual functions, member functions, classes ... Only structs with PODs in it are allowed.

Some exceptions to the rules:

  • You are writing a standard library with advanced data structures where malloc is appropriate
  • You have to allocate big amounts of memory (In memory copy of a 10GB file?)
  • You have tooling preventing you to use certain constructs
  • You need to store an incomplete type

How to handle the modal closing event in Twitter Bootstrap?

If you want specifically do something when click on close button exactly like you described:

<a href="#" class="btn close_link" data-dismiss="modal">Close</a>

you need to attach an event using css selector:

$(document).on('click', '[data-dismiss="modal"]', function(){what you want to do})

But if you want to do something when modal close, you can use the already wrote tips

Create an array with same element repeated multiple times

In ES6 using Array fill() method

Array(5).fill(2)
//=> [2, 2, 2, 2, 2]

div with dynamic min-height based on browser window height

to get dynamic height based on browser window. Use vh instead of %

e.g: pass following height: 100vh; to the specific div

Bootstrap button drop-down inside responsive table not visible because of scroll

This worked for me in Bootstrap 4 since it has different breakpoints than v3:

@media (min-width: 992px) {
    .table-responsive {
        overflow: inherit;
    }
}

Http Post With Body

 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

then add elements for each pair

 nameValuePairs.add(new BasicNameValuePair("yourReqVar", Value);
 nameValuePairs.add( ..... );

Then use the HttpPost:

HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

and use the HttpClient and Response to get the response from the server

How to change indentation in Visual Studio Code?

How to turn 4 spaces indents in all files in VS Code to 2 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(?: {2})(\b|(?!=[,'";\.:\*\\\/\{\}\[\]\(\)])) in the search field
  • Enter: $1 in the replace field

How to turn 2 spaces indents in all files in VS Code to 4 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(\b|(?!=[,'";\.:\\*\\\/{\}\[\]\(\)])) in the search field
  • Enter: $1$1 in the replace field

NOTE: You must turn on PERL Regex first. This is How:

  • Open settings and go to the JSON file
  • add the following to the JSON file "search.usePCRE2": true

Hope someone sees this.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

How do I change the IntelliJ IDEA default JDK?

I have found out that in recent versions of IntelliJ IDEA requires Java 1.8 but is not configured by default.

We can change the path or configure from Project Settings > Project > Project SDK

here we can edit or add the JDK´s path.

(in my case the path is located in C:\Program Files\Java\jdk1.8.0_102)

enter image description here

enter image description here

Using Linq to group a list of objects into a new grouped list of list of objects

var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .Select(grp => grp.ToList())
    .ToList();

get list of pandas dataframe columns based on data type

As of pandas v0.14.1, you can utilize select_dtypes() to select columns by dtype

In [2]: df = pd.DataFrame({'NAME': list('abcdef'),
    'On_Time': [True, False] * 3,
    'On_Budget': [False, True] * 3})

In [3]: df.select_dtypes(include=['bool'])
Out[3]:
  On_Budget On_Time
0     False    True
1      True   False
2     False    True
3      True   False
4     False    True
5      True   False

In [4]: mylist = list(df.select_dtypes(include=['bool']).columns)

In [5]: mylist
Out[5]: ['On_Budget', 'On_Time']

Set initial focus in an Android application

android:focusedByDefault="true"

How can I make a menubar fixed on the top while scrolling

The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

Please see CSS postion attribute documentation when you can :)

How to get parameters from a URL string?

A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.

How to import keras from tf.keras in Tensorflow?

Try from tensorflow.python import keras

with this, you can easily change keras dependent code to tensorflow in one line change.

You can also try from tensorflow.contrib import keras. This works on tensorflow 1.3

Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras to get keras in tensorflow.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

Simplify things by using the following settings.xml:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">

 <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user</username>  <!-- Put your username here -->
      <password>pass</password>  <!-- Put your password here -->
      <host>123.45.6.78</host>   <!-- Put the IP address of your proxy server here -->
      <port>80</port>            <!-- Put your proxy server's port number here -->
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts> <!-- Do not use this setting unless you know what you're doing. -->
    </proxy>    
  </proxies> 
</settings>

Under Linux/Unix, place it under ~/.m2/settings.xml. Under Windows place it under c:\documents and settings\youruser\.m2\settings.xml or c:\users\youruser\.m2\settings.xml.

You don't need the <mirrors/>, <profiles/> and <settings/> sections, unless you really know what they're for.

What is the size of a boolean variable in Java?

It's virtual machine dependent.

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

If your URL contains words such as "advert", "ad", "doubleclick", "click", or something similar…

For example:

  • GET googleads.g.doubleclick.net/pagead/id
  • static.doubleclick.net/instream/ad_status.js

…Then ad-blocker will block it.

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

Regular expressions inside SQL Server

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'

How can VBA connect to MySQL database in Excel?

This piece of vba worked for me:

Sub connect()
    Dim Password As String
    Dim SQLStr As String
    'OMIT Dim Cn statement
    Dim Server_Name As String
    Dim User_ID As String
    Dim Database_Name As String
    'OMIT Dim rs statement

    Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
    Server_Name = Range("b2").Value
    Database_name = Range("b3").Value ' Name of database
    User_ID = Range("b4").Value 'id user or username
    Password = Range("b5").Value 'Password

    SQLStr = "SELECT * FROM ComputingNotesTable"

    Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
    Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _ 
            Server_Name & ";Database=" & Database_Name & _
            ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic

    Dim myArray()

    myArray = rs.GetRows()

    kolumner = UBound(myArray, 1)
    rader = UBound(myArray, 2)

    For K = 0 To kolumner ' Using For loop data are displayed
        Range("a5").Offset(0, K).Value = rs.Fields(K).Name
        For R = 0 To rader
           Range("A5").Offset(R + 1, K).Value = myArray(K, R)
        Next
    Next

    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

Change the borderColor of the TextBox

With PictureBox1
    .Visible = False
    .Width = TextBox1.Width + 4
    .Height = TextBox1.Height + 4
    .Left = TextBox1.Left - 2
    .Top = TextBox1.Top - 2
    .SendToBack()
    .Visible = True
End With

Convert comma separated string of ints to int array

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input: 2,3 1,2,3 2,4,6 will store values as arr = {{1,2,3},{2,4,6}};

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

Is it possible to run .APK/Android apps on iPad/iPhone devices?

The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.

Show compose SMS view in Android

You can use this to send sms to any number:

 public void sendsms(View view) {
        String phoneNumber = "+880xxxxxxxxxx";
        String message = "Welcome to sms";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + phoneNumber));
        intent.putExtra("sms_body", message);
        startActivity(intent);
    }

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

The requested resource does not support HTTP method 'GET'

I was experiencing the same issue.. I already had 4 controllers going and working just fine but when I added this one it returned "The requested resource does not support HTTP method 'GET'". I tried everything here and in a couple other relevant articles but was indifferent to the solution since, as Dan B. mentioned in response to the answer, I already had others working fine.

I walked away for a while, came back, and immediately realized that when I added the Controller it was nested under the "Controller" class and not "ApiController" class that my other Controllers were under. I'm assuming I chose the wrong scaffolding option to build the .cs file in Visual Studio. So I included the System.Web.Http namespace, changed the parent class, and everything works without the additional attributes or routing.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I think this might help.

SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Aesthetics must either be length one, or the same length as the dataProblems

The problem is that skew isn't being subsetted in colour=factor(skew), so it's the wrong length. Since subset(skew, product == 'p1') is the same as subset(skew, product == 'p3'), in this case it doesn't matter which subset is used. So you can solve your problem with:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

Note that most R users would write this as the more concise:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

How to get the android Path string to a file on Assets folder?

Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:

@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
    val cacheFile = File(context.cacheDir, "splash_video")
    try {
        val inputStream = context.assets.open("splash_video")
        val outputStream = FileOutputStream(cacheFile)
        try {
            inputStream.copyTo(outputStream)
        } finally {
            inputStream.close()
            outputStream.close()
        }
    } catch (e: IOException) {
        throw IOException("Could not open splash_video", e)
    }
    return cacheFile
}

Best way to combine two or more byte arrays in C#

For primitive types (including bytes), use System.Buffer.BlockCopy instead of System.Array.Copy. It's faster.

I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:

  1. New Byte Array using System.Array.Copy - 0.2187556 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.1406286 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0781270 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781270 seconds

I increased the size of each array to 100 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 0.2812554 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.2500048 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

I increased the size of each array to 1000 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 1.0781457 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 1.0156445 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

Finally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:

  1. New Byte Array using System.Array.Copy - 13.4533833 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 13.1096267 seconds
  3. IEnumerable<byte> using C# yield operator - 0 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0 seconds

So, if you need a new byte array, use

byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);

But, if you can use an IEnumerable<byte>, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.

IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);

If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy solution more generic like this:

private byte[] Combine(params byte[][] arrays)
{
    byte[] rv = new byte[arrays.Sum(a => a.Length)];
    int offset = 0;
    foreach (byte[] array in arrays) {
        System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
        offset += array.Length;
    }
    return rv;
}

*Note: The above block requires you adding the following namespace at the the top for it to work.

using System.Linq;

To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:

  1. New Byte Array using System.Array.Copy - 78.20550510 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 77.89261900 seconds
  3. IEnumerable<byte> using C# yield operator - 551.7150161 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 448.1804799 seconds

The point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

For the UPDATE

Use:

UPDATE table1 
   SET col1 = othertable.col2,
       col2 = othertable.col3 
  FROM othertable 
 WHERE othertable.col1 = 123;

For the INSERT

Use:

INSERT INTO table1 (col1, col2) 
SELECT col1, col2 
  FROM othertable

You don't need the VALUES syntax if you are using a SELECT to populate the INSERT values.

How can I filter a date of a DateTimeField in Django?

YourModel.objects.filter(datetime_published__year='2008', 
                         datetime_published__month='03', 
                         datetime_published__day='27')

// edit after comments

YourModel.objects.filter(datetime_published=datetime(2008, 03, 27))

doest not work because it creates a datetime object with time values set to 0, so the time in database doesn't match.

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

How to check if bootstrap modal is open, so I can use jquery validate?

You can also directly use jQuery.

$('#myModal').is(':visible');

break/exit script

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}

How to hide/show div tags using JavaScript?

Consider using jQuery. Life is much easier with:

$('body').hide(); $('body1').show();

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

How to check if two arrays are equal with JavaScript?

[2021 changelog: bugfix for option4: no total ordering on js objects (even excluding NaN!=NaN and '5'==5 ('5'===5, '2'<3, etc.)), so cannot use .sort on Map.keys() (though you can on Object.keys(obj), since even 'numerical' keys are strings)]

Option 1

Easiest option, works in almost all cases, except that null!==undefined but they both are converted to JSON representation null and considered equal:

function arraysEqual(a1,a2) {
    /* WARNING: arrays must not contain {objects} or behavior may be undefined */
    return JSON.stringify(a1)==JSON.stringify(a2);
}

(This might not work if your array contains objects. Whether this still works with objects depends on whether the JSON implementation sorts keys. For example, the JSON of {1:2,3:4} may or may not be equal to {3:4,1:2}; this depends on the implementation, and the spec makes no guarantee whatsoever. [2017 update: Actually the ES6 specification now guarantees object keys will be iterated in order of 1) integer properties, 2) properties in the order they were defined, then 3) symbol properties in the order they were defined. Thus IF the JSON.stringify implementation follows this, equal objects (in the === sense but NOT NECESSARILY in the == sense) will stringify to equal values. More research needed. So I guess you could make an evil clone of an object with properties in the reverse order, but I cannot imagine it ever happening by accident...] At least on Chrome, the JSON.stringify function tends to return keys in the order they were defined (at least that I've noticed), but this behavior is very much subject to change at any point and should not be relied upon. If you choose not to use objects in your lists, this should work fine. If you do have objects in your list that all have a unique id, you can do a1.map(function(x)}{return {id:x.uniqueId}}). If you have arbitrary objects in your list, you can read on for option #2.)

This works for nested arrays as well.

It is, however, slightly inefficient because of the overhead of creating these strings and garbage-collecting them.


Option 2

More "proper" option, which you can override to deal with special cases (like regular objects and null/undefined and custom objects, if you so desire):

// generally useful functions
function type(x) { // does not work in general, but works on JSONable objects we care about... modify as you see fit
    // e.g.  type(/asdf/g) --> "[object RegExp]"
    return Object.prototype.toString.call(x);
}
function zip(arrays) {
    // e.g. zip([[1,2,3],[4,5,6]]) --> [[1,4],[2,5],[3,6]]
    return arrays[0].map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });
}

 

// helper functions
function allCompareEqual(array) {
    // e.g.  allCompareEqual([2,2,2,2]) --> true
    // does not work with nested arrays or objects
    return array.every(function(x){return x==array[0]});
}

function isArray(x){ return type(x)==type([]) }
function getLength(x){ return x.length }
function allTrue(array){ return array.reduce(function(a,b){return a&&b},true) }
    // e.g. allTrue([true,true,true,true]) --> true
    // or just array.every(function(x){return x});

 

function allDeepEqual(things) {
    // works with nested arrays
    if( things.every(isArray) )
        return allCompareEqual(things.map(getLength))     // all arrays of same length
               && allTrue(zip(things).map(allDeepEqual)); // elements recursively equal

    //else if( this.every(isObject) )
    //  return {all have exactly same keys, and for 
    //          each key k, allDeepEqual([o1[k],o2[k],...])}
    //  e.g. ... && allTrue(objectZip(objects).map(allDeepEqual)) 

    //else if( ... )
    //  extend some more

    else
        return allCompareEqual(things);
}

Demo:

allDeepEqual([ [], [], [] ])
true
allDeepEqual([ [1], [1], [1] ])
true
allDeepEqual([ [1,2], [1,2] ])
true
allDeepEqual([ [[1,2],[3]], [[1,2],[3]] ])
true

allDeepEqual([ [1,2,3], [1,2,3,4] ])
false
allDeepEqual([ [[1,2],[3]], [[1,2],[],3] ])
false
allDeepEqual([ [[1,2],[3]], [[1],[2,3]] ])
false
allDeepEqual([ [[1,2],3], [1,[2,3]] ])
false

To use this like a regular function, do:

function allDeepEqual2() {
    return allDeepEqual([].slice.call(arguments));
}

Demo:

allDeepEqual2([[1,2],3], [[1,2],3])
true

Options 3

edit: It's 2016 and my previous overcomplicated answer was bugging me. This recursive, imperative "recursive programming 101" implementation keeps the code really simple, and furthermore fails at the earliest possible point (giving us efficiency). It also doesn't generate superfluous ephemeral datastructures (not that there's anything wrong with functional programming in general, but just keeping it clean here).

If we wanted to apply this to a non-empty arrays of arrays, we could do seriesOfArrays.reduce(arraysEqual).

This is its own function, as opposed to using Object.defineProperties to attach to Array.prototype, since that would fail with a key error if we passed in an undefined value (that is however a fine design decision if you want to do so).

This only answers OPs original question.

function arraysEqual(a,b) {
    /*
        Array-aware equality checker:
        Returns whether arguments a and b are == to each other;
        however if they are equal-lengthed arrays, returns whether their 
        elements are pairwise == to each other recursively under this
        definition.
    */
    if (a instanceof Array && b instanceof Array) {
        if (a.length!=b.length)  // assert same length
            return false;
        for(var i=0; i<a.length; i++)  // assert each element equal
            if (!arraysEqual(a[i],b[i]))
                return false;
        return true;
    } else {
        return a==b;  // if not both arrays, should be the same
    }
}

Examples:

arraysEqual([[1,2],3], [[1,2],3])
true
arraysEqual([1,2,3], [1,2,3,4])
false
arraysEqual([[1,2],[3]], [[1,2],[],3])
false
arraysEqual([[1,2],[3]], [[1],[2,3]])
false
arraysEqual([[1,2],3], undefined)
false
arraysEqual(undefined, undefined)
true
arraysEqual(1, 2)
false
arraysEqual(null, null)
true
arraysEqual(1, 1)
true
arraysEqual([], 1)
false
arraysEqual([], undefined)
false
arraysEqual([], [])
true

If you wanted to apply this to JSON-like data structures with js Objects, you could do so. Fortunately we're guaranteed that all objects keys are unique, so iterate over the objects OwnProperties and sort them by key, then assert that both the sorted key-array is equal and the value-array are equal, and just recurse. We can extend this to include Maps as well (where the keys are also unique). (However if we extend this to Sets, we run into the tree isomorphism problem http://logic.pdmi.ras.ru/~smal/files/smal_jass08_slides.pdf - fortunately it's not as hard as general graph isomorphism; there is in fact an O(#vertices) algorithm to solve it, but it can get very complicated to do it efficiently. The pathological case is if you have a set made up of lots of seemingly-indistinguishable objects, but upon further inspection some of those objects may differ as you delve deeper into them. You can also work around this by using hashing to reject almost all cases.)


Option 4: (continuation of 2016 edit)

This should work with most objects:

const STRICT_EQUALITY = (a,b)=> a===b;
function deepEquals(a,b, areEqual=STRICT_EQUALITY) {
    /* compares objects hierarchically using the provided 
       notion of equality (defaulting to ===);
       supports Arrays, Objects, Maps, ArrayBuffers */
    if (a instanceof Array && b instanceof Array)
        return arraysEqual(a,b, areEqual);
    if (Object.getPrototypeOf(a)===Object.prototype && Object.getPrototypeOf(b)===Object.prototype)
        return objectsEqual(a,b, areEqual);
    if (a instanceof Map && b instanceof Map)
        return mapsEqual(a,b, areEqual);        
    if (a instanceof Set && b instanceof Set) {
        if (areEquals===STRICT_EQUALITY)
            return setsEqual(a,b);
        else
            throw "Error: set equality by hashing not implemented because cannot guarantee custom notion of equality is transitive without programmer intervention."
    }
    if ((a instanceof ArrayBuffer || ArrayBuffer.isView(a)) && (b instanceof ArrayBuffer || ArrayBuffer.isView(b)))
        return typedArraysEqual(a,b);
    return areEqual(a,b);  // see note[1] -- IMPORTANT
}

function arraysEqual(a,b, areEqual) {
    if (a.length!=b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (!deepEquals(a[i],b[i], areEqual))
            return false;
    return true;
}
function objectsEqual(a,b, areEqual) {
    var aKeys = Object.getOwnPropertyNames(a);
    var bKeys = Object.getOwnPropertyNames(b);
    if (aKeys.length!=bKeys.length)
        return false;
    aKeys.sort();
    bKeys.sort();
    for(var i=0; i<aKeys.length; i++)
        if (!areEqual(aKeys[i],bKeys[i])) // keys must be strings
            return false;
    return deepEquals(aKeys.map(k=>a[k]), aKeys.map(k=>b[k]), areEqual);
}
function mapsEqual(a,b, areEqual) { // assumes Map's keys use the '===' notion of equality, which is also the assumption of .has and .get methods in the spec; however, Map's values use our notion of the areEqual parameter
    if (a.size!=b.size)
        return false;
    return [...a.keys()].every(k=> 
        b.has(k) && deepEquals(a.get(k), b.get(k), areEqual)
    );
}
function setsEqual(a,b) {
    // see discussion in below rest of StackOverflow answer
    return a.size==b.size && [...a.keys()].every(k=> 
        b.has(k)
    );
}
function typedArraysEqual(a,b) {
    // we use the obvious notion of equality for binary data
    a = new Uint8Array(a);
    b = new Uint8Array(b);
    if (a.length != b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (a[i]!=b[i])
            return false;
    return true;
}

Demo (not extensively tested):

var nineTen = new Float32Array(2);
nineTen[0]=9; nineTen[1]=10;

> deepEquals(
    [[1,[2,3]], 4, {a:5,'111':6}, new Map([['c',7],['d',8]]), nineTen],
    [[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen]
)
true

> deepEquals(
    [[1,[2,3]], 4, {a:'5','111':6}, new Map([['c',7],['d',8]]), nineTen],
    [[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen],
    (a,b)=>a==b
)
true

Note that if one is using the == notion of equality, then know that falsey values and coercion means that == equality is NOT TRANSITIVE. For example ''==0 and 0=='0' but ''!='0'. This is relevant for Sets: I do not think one can override the notion of Set equality in a meaningful way. If one is using the built-in notion of Set equality (that is, ===), then the above should work. However if one uses a non-transitive notion of equality like ==, you open a can of worms: Even if you forced the user to define a hash function on the domain (hash(a)!=hash(b) implies a!=b) I'm not sure that would help... Certainly one could do the O(N^2) performance thing and remove pairs of == items one by one like a bubble sort, and then do a second O(N^2) pass to confirm things in equivalence classes are actually == to each other, and also != to everything not thus paired, but you'd STILL have to throw a runtime error if you have some coercion going on... You'd also maybe get weird (but potentially not that weird) edge cases with https://developer.mozilla.org/en-US/docs/Glossary/Falsy and Truthy values (with the exception that NaN==NaN... but just for Sets!). This is not an issue usually with most Sets of homogenous datatype.

(sidenote: Maps are es6 dictionaries. I can't tell if they have O(1) or O(log(N)) lookup performance, but in any case they are 'ordered' in the sense that they keep track of the order in which key-value pairs were inserted into them. However, the semantic of whether two Maps should be equal if elements were inserted in a different order into them is ambiguous. I give a sample implementation below of a deepEquals that considers two maps equal even if elements were inserted into them in a different order.)

(note [1]: IMPORTANT: NOTION OF EQUALITY: You may want to override the noted line with a custom notion of equality, which you'll also have to change in the other functions anywhere it appears. For example, do you or don't you want NaN==NaN? By default this is not the case. There are even more weird things like 0=='0'. Do you consider two objects to be the same if and only if they are the same object in memory? See https://stackoverflow.com/a/5447170/711085 . You should document the notion of equality you use. )

You should be able to extend the above to WeakMaps, WeakSets. Not sure if it makes sense to extend to DataViews. Should also be able to extend to RegExps probably, etc.

As you extend it, you realize you do lots of unnecessary comparisons. This is where the type function that I defined way earlier (solution #2) can come in handy; then you can dispatch instantly. Whether that is worth the overhead of (possibly? not sure how it works under the hood) string representing the type is up to you. You can just then rewrite the dispatcher, i.e. the function deepEquals, to be something like:

var dispatchTypeEquals = {
    number: function(a,b) {...a==b...},
    array: function(a,b) {...deepEquals(x,y)...},
    ...
}
function deepEquals(a,b) {
    var typeA = extractType(a);
    var typeB = extractType(a);
    return typeA==typeB && dispatchTypeEquals[typeA](a,b);
}

React Native: Possible unhandled promise rejection

In My case, I am running a local Django backend in IP 127.0.0.1:8000 with Expo start. Just make sure you have the server in public domain not hosted lcoally on your machine

fatal error LNK1104: cannot open file 'kernel32.lib'

I got a similar error, the problem stopped when I checked my "Linker -> Input -> Additional Dependencies" list in the project properties. I was missing a semi colon ";" just before "%(AdditionalDependencies)". I also had the same entry in twice. You should edit this list separately for Debug and Release.

How to create a multi line body in C# System.Net.Mail.MailMessage

You need to enable IsBodyHTML

message.IsBodyHtml = true; //This will enable using HTML elements in email body
message.Body ="First Line <br /> second line";

How to replace ${} placeholders in a text file?

file.tpl:

The following bash function should only replace ${var1} syntax and ignore 
other shell special chars such as `backticks` or $var2 or "double quotes". 
If I have missed anything - let me know.

script.sh:

template(){
    # usage: template file.tpl
    while read -r line ; do
            line=${line//\"/\\\"}
            line=${line//\`/\\\`}
            line=${line//\$/\\\$}
            line=${line//\\\${/\${}
            eval "echo \"$line\""; 
    done < ${1}
}

var1="*replaced*"
var2="*not replaced*"

template file.tpl > result.txt

./xx.py: line 1: import: command not found

When you see "import: command not found" on the very first import, it is caused by the parser not using the character encoding matching your py file. Especially when you are not using ASCII encoding in your py file.

The way to get it right is to specify the correct encoding on top of your py file to match your file character encoding.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

JavaScript OOP in NodeJS: how?

As Node.js community ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner.

You can take a look at JavaScript classes. MDN link to JS classes In the ECMAScript 6 JavaScript classes are introduced, this method provide easier way to model OOP concepts in Javascript.

Note : JS classes will work in only strict mode.

Below is some skeleton of class,inheritance written in Node.js ( Used Node.js Version v5.0.0 )

Class declarations :

'use strict'; 
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

var a1 = new Animal('Dog');

Inheritance :

'use strict';
class Base{

 constructor(){
 }
 // methods definitions go here
}

class Child extends Base{
 // methods definitions go here
 print(){ 
 }
}

var childObj = new Child();

Vertically align an image inside a div with responsive height

Here is a technique to align inline elements inside a parent, horizontally and vertically at the same time:

Vertical Alignment

1) In this approach, we create an inline-block (pseudo-)element as the first (or last) child of the parent, and set its height property to 100% to take all the height of its parent.

2) Also, adding vertical-align: middle keeps the inline(-block) elements at the middle of the line space. So, we add that CSS declaration to the first-child and our element (the image) both.

3) Finally, in order to remove the white space character between inline(-block) elements, we could set the font size of the parent to zero by font-size: 0;.

Note: I used Nicolas Gallagher's image replacement technique in the following.

What are the benefits?

  • The container (parent) can have dynamic dimensions.
  • There's no need to specify the dimensions of the image element explicitly.

  • We can easily use this approach to align a <div> element vertically as well; which may have a dynamic content (height and/or width). But note that you have to re-set the font-size property of the div to display the inside text. Online Demo.

<div class="container">
    <div id="element"> ... </div>
</div>
.container {
    height: 300px;
    text-align: center;  /* align the inline(-block) elements horizontally */
    font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.container:before {    /* create a full-height inline block pseudo=element */
    content: ' ';
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    height: 100%;
}

#element {
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    font: 16px/1 Arial sans-serif;        /* <-- reset the font property */
}

The output

Vertically align an element in its container

Responsive Container

This section is not going to answer the question as the OP already knows how to create a responsive container. However, I'll explain how it works.

In order to make the height of a container element changes with its width (respecting the aspect ratio), we could use a percentage value for top/bottom padding property.

A percentage value on top/bottom padding or margins is relative to the width of the containing block.

For instance:

.responsive-container {
  width: 60%;

  padding-top: 60%;    /* 1:1 Height is the same as the width */
  padding-top: 100%;   /* width:height = 60:100 or 3:5        */
  padding-top: 45%;    /* = 60% * 3/4 , width:height =  4:3   */
  padding-top: 33.75%; /* = 60% * 9/16, width:height = 16:9   */
}

Here is the Online Demo. Comment out the lines from the bottom and resize the panel to see the effect.

Also, we could apply the padding property to a dummy child or :before/:after pseudo-element to achieve the same result. But note that in this case, the percentage value on padding is relative to the width of the .responsive-container itself.

<div class="responsive-container">
  <div class="dummy"></div>
</div>
.responsive-container { width: 60%; }

.responsive-container .dummy {
  padding-top: 100%;    /*  1:1 square */
  padding-top: 75%;     /*  w:h =  4:3 */
  padding-top: 56.25%;  /*  w:h = 16:9 */
}

Demo #1.
Demo #2 (Using :after pseudo-element)

Adding the content

Using padding-top property causes a huge space at the top or bottom of the content, inside the container.

In order to fix that, we have wrap the content by a wrapper element, remove that element from document normal flow by using absolute positioning, and finally expand the wrapper (bu using top, right, bottom and left properties) to fill the entire space of its parent, the container.

Here we go:

.responsive-container {
  width: 60%;
  position: relative;
}

.responsive-container .wrapper {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

Here is the Online Demo.


Getting all together

<div class="responsive-container">
  <div class="dummy"></div>

  <div class="img-container">
    <img src="http://placehold.it/150x150" alt="">
  </div>
</div>
.img-container {
  text-align:center; /* Align center inline elements */
  font: 0/0 a;       /* Hide the characters like spaces */
}

.img-container:before {
  content: ' ';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.img-container img {
  vertical-align: middle;
  display: inline-block;
}

Here is the WORKING DEMO.

Obviously, you could avoid using ::before pseudo-element for browser compatibility, and create an element as the first child of the .img-container:

<div class="img-container">
    <div class="centerer"></div>
    <img src="http://placehold.it/150x150" alt="">
</div>
.img-container .centerer {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

UPDATED DEMO.

Using max-* properties

In order to keep the image inside of the box in lower width, you could set max-height and max-width property on the image:

.img-container img {
    vertical-align: middle;
    display: inline-block;
    max-height: 100%;  /* <-- Set maximum height to 100% of its parent */
    max-width: 100%;   /* <-- Set maximum width to 100% of its parent */
}

Here is the UPDATED DEMO.

How can I determine the status of a job?

;WITH CTE_JobStatus
AS (
    SELECT DISTINCT NAME AS [JobName]
        ,s.step_id
        ,s.step_name
        ,CASE 
            WHEN [Enabled] = 1
                THEN 'Enabled'
            ELSE 'Disabled'
            END [JobStatus]
        ,CASE 
            WHEN SJH.run_status = 0
                THEN 'Failed'
            WHEN SJH.run_status = 1
                THEN 'Succeeded'
            WHEN SJH.run_status = 2
                THEN 'Retry'
            WHEN SJH.run_status = 3
                THEN 'Cancelled'
            WHEN SJH.run_status = 4
                THEN 'In Progress'
            ELSE 'Unknown'
            END [JobOutcome]
        ,CONVERT(VARCHAR(8), sjh.run_date) [RunDate]
        ,CONVERT(VARCHAR(8), STUFF(STUFF(CONVERT(TIMESTAMP, RIGHT('000000' + CONVERT(VARCHAR(6), sjh.run_time), 6)), 3, 0, ':'), 6, 0, ':')) RunTime
        ,RANK() OVER (
            PARTITION BY s.step_name ORDER BY sjh.run_date DESC
                ,sjh.run_time DESC
            ) AS rn
        ,SJH.run_status
    FROM msdb..SYSJobs sj
    INNER JOIN msdb..SYSJobHistory sjh ON sj.job_id = sjh.job_id
    INNER JOIN msdb.dbo.sysjobsteps s ON sjh.job_id = s.job_id
        AND sjh.step_id = s.step_id
    WHERE (sj.NAME LIKE 'JOB NAME')
        AND sjh.run_date = CONVERT(CHAR, getdate(), 112)
    )
SELECT *
FROM CTE_JobStatus
WHERE rn = 1
    AND run_status NOT IN (1,4)

isPrime Function for Python Language

I have a new solution which I think might be faster than any of the mentioned Function in Python

It's based on the idea that: N/D = R for any arbitrary number N, the least possible number to divide N (if not prime) is D=2 and the corresponding result R is (N/2) (highest).

As D goes bigger the result R gets smaller ex: divide by D = 3 results R = (N/3) so when we are checking if N is divisible by D we are also checking if it's divisible by R

so as D goes bigger and R goes smaller till (D == R == square root(N))

then we only need to check numbers from 2 to sqrt(N) another tip to save time, we only need to check the odd numbers as it the number is divisible by any even number it will also be divisible by 2.

so the sequence will be 3,5,7,9,......,sqrt(N).

import math
def IsPrime (n): 
    if (n <= 1 or n % 2 == 0):return False
    if n == 2:return True
    for i in range(3,int(math.sqrt(n))+1,2):
        if (n % i) == 0:
            return False
    return True

How to run test cases in a specified file?

alias testcases="sed -n 's/func.*\(Test.*\)(.*/\1/p' | xargs | sed 's/ /|/g'"

go test -v -run $(cat coordinator_test.go | testcases)

How to use if - else structure in a batch file?

I believe you can use something such as

if ___ (

do this

) else if ___ (

do this

)

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I'll add my answer as an example1 that might help you better understand the difference.

Let's suppose we want to create an image that will always run a sleep command when it starts. We'll create our own image and specify a new command:

FROM ubuntu
CMD sleep 10

Building the image:

docker build -t custom_sleep .
docker run custom_sleep
# sleeps for 10 seconds and exits

What if we want to change the number of seconds? We would have to change the Dockerfile since the value is hardcoded there, or override the command by providing a different one:

docker run custom_sleep sleep 20

While this works, it's not a good solution, as we have a redundant "sleep" command. Why redundant? Because the container's only purpose is to sleep, so having to specify the sleep command explicitly is a bit awkward.

Now let's try using the ENTRYPOINT instruction:

FROM ubuntu
ENTRYPOINT sleep

This instruction specifies the program that will be run when the container starts.

Now we can run:

docker run custom_sleep 20

What about a default value? Well, you guessed it right:

FROM ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]

The ENTRYPOINT is the program that will be run, and the value passed to the container will be appended to it.

The ENTRYPOINT can be overridden by specifying an --entrypoint flag, followed by the new entry point you want to use.

Not mine, I once watched a tutorial that provided this example

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Check this out :

http://jsfiddle.net/PTbGc/

Your issue seems to have been fixed.


What shows up for me (under Chrome and Mac OS X)

1. one
2. two
  2.1. two.one
  2.2. two.two
  2.3. two.three
3. three
  3.1 three.one
  3.2 three.two
    3.2.1 three.two.one
    3.2.2 three.two.two
4. four

How I did it


Instead of :

<li>Item 1</li>
<li>Item 2</li>
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>

Do :

<li>Item 1</li>
<li>Item 2
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>
</li>

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

ULIMIT configuration:

  1. Login by root
  2. vi security/limits.conf
  3. Make Below entry

    Ulimit configuration start for website user

    website   soft   nofile    8192
    website   hard   nofile    8192
    website   soft   nproc    4096
    website   hard   nproc    8192
    website   soft   core    unlimited
    website   hard   core    unlimited
    
  4. Make Below entry for ALL USER

    Ulimit configuration for every user

    *   soft   nofile    8192
    *   hard   nofile    8192
    *   soft   nproc    4096
    *   hard   nproc    8192
    *   soft   core    unlimited
    *   hard   core    unlimited
    
  5. After modifying the file, user need to logoff and login again to see the new values.

Rebuild all indexes in a Database

Replace the "YOUR DATABASE NAME" in the query below.

    DECLARE @Database NVARCHAR(255)   
    DECLARE @Table NVARCHAR(255)  
    DECLARE @cmd NVARCHAR(1000)  

    DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
    SELECT name FROM master.sys.databases   
    WHERE name IN ('YOUR DATABASE NAME')  -- databases
    AND state = 0 -- database is online
    AND is_in_standby = 0 -- database is not read only for log shipping
    ORDER BY 1  

    OPEN DatabaseCursor  

    FETCH NEXT FROM DatabaseCursor INTO @Database  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  

       SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
       table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

       -- create table cursor  
       EXEC (@cmd)  
       OPEN TableCursor   

       FETCH NEXT FROM TableCursor INTO @Table   
       WHILE @@FETCH_STATUS = 0   
       BEGIN
          BEGIN TRY   
             SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
             PRINT @cmd -- uncomment if you want to see commands
             EXEC (@cmd) 
          END TRY
          BEGIN CATCH
             PRINT '---'
             PRINT @cmd
             PRINT ERROR_MESSAGE() 
             PRINT '---'
          END CATCH

          FETCH NEXT FROM TableCursor INTO @Table   
       END   

       CLOSE TableCursor   
       DEALLOCATE TableCursor  

       FETCH NEXT FROM DatabaseCursor INTO @Database  
    END  
    CLOSE DatabaseCursor   
    DEALLOCATE DatabaseCursor

how to get last insert id after insert query in codeigniter active record

Try this

function add_post($post_data){
   $this->db->insert('posts', $post_data);
   $insert_id = $this->db->insert_id();

   return  $insert_id;
}

In case of multiple inserts you could use

$this->db->trans_start();
$this->db->trans_complete();

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Spring MVC - How to get all request params in a map in Spring controller?

Here is the simple example of getting request params in a Map.

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
       {
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );
       }

In this case, it will bind the value of studentName and studentEmail with name and email variables respectively.

login to remote using "mstsc /admin" with password

It became a popular question and I got a notification. I am sorry, I forgot to answer before which I should have done. I solved it long back.

net use \\10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes

Run it in a batch file and you should get what you are looking for.

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

Spring @ContextConfiguration how to put the right location for the xml

This is a maven specific problem I think. Maven does not copy the files form /src/main/resources to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.

An easier way is to instead put a test specific context definition in the /src/test/resources directory and load via:

@ContextConfiguration(locations = { "classpath:mycontext.xml" })

How do I make a C++ console program exit?

throw back to main which should return EXIT_FAILURE,

or std::terminate() if corrupted.

(from Martin York's comment)

TensorFlow: "Attempting to use uninitialized value" in variable initialization

I want to give my resolution, it work when i replace the line [session = tf.Session()] with [sess = tf.InteractiveSession()]. Hope this will be useful to others.

Regular Expressions- Match Anything

Choose & memorize 1 of the following!!! :)

[\s\S]*
[\w\W]*
[\d\D]*

Explanation:

\s: whitespace \S: not whitespace

\w: word \W: not word

\d: digit \D: not digit

(You can exchange the * for + if you want 1 or MORE characters [instead of 0 or more]).




BONUS EDIT:

If you want to match everything on a single line, you can use this:

[^\n]+

Explanation:

^: not

\n: linebreak

+: for 1 character or more

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

Does Ruby have a string.startswith("abc") built in method?

You can use String =~ Regex. It returns position of full regex match in string.

irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false

How to disable a link using only CSS?

It's possible to do it in CSS

_x000D_
_x000D_
.disabled{_x000D_
  cursor:default;_x000D_
  pointer-events:none;_x000D_
  text-decoration:none;_x000D_
  color:black;_x000D_
}
_x000D_
<a href="https://www.google.com" target="_blank" class="disabled">Google</a>
_x000D_
_x000D_
_x000D_

See at:

Please note that the text-decoration: none; and color: black; is not needed but it makes the link look more like plain text.

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

What's the easiest way to call a function every 5 seconds in jQuery?

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suites you most and how to stop each of them.

How to set a DateTime variable in SQL Server 2008?

 1. I create new Date() and convert her in String .
 2. This string I set in insert.

 **Example:**  insert into newDate(date_create) VALUES (?)";

 ...
 PreparedStatement ps = con.prepareStatement(CREATE))
        ps.setString(1, getData());
        ps.executeUpdate();
  ...}

   private String getData() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd hh:mm:ss");
     return  sdf.format(new java.util.Date());
    }

 **It is very important format** = "yyyy-M-dd hh:mm:ss"

Using Google Text-To-Speech in Javascript

Here is the code snippet I found:

var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

How to write PNG image to string with the PIL?

sth's solution didn't work for me
because in ...

Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension

It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case

You can bypass the format detection by setting the format yourself in a parameter

import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

How to use Tomcat 8 in Eclipse?

To add the Tomcat 9.0 (Tomcat build from the trunk) as a server in Eclipse.

Update the ServerInfo.properties file properties as below.

server.info=Apache Tomcat/@VERSION@
server.number=@VERSION_NUMBER@
server.built=@VERSION_BUILT@


server.info=Apache Tomcat/7.0.57
server.number=7.0.57.0
server.built=Nov 3 2014 08:39:16 UTC

Build the tomcat server from trunk and add the server as tomcat7 instance in Eclipse.

ServerInfo.properties file location : \tomcat\java\org\apache\catalina\util\ServerInfo.properties

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How do you divide each element in a list by an int?

>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Accessing certain pixel RGB value in openCV

The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame, you could get the blue value at location (x, y) (from the top left) this way:

frame.data[frame.channels()*(frame.cols*y + x)];

Likewise, to get B, G, and R:

uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];    
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];

Note that this code assumes the stride is equal to the width of the image.

Unsafe JavaScript attempt to access frame with URL

I was getting the same error message when I tried to change the domain for iframe.src.

For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.

Worked like a charm.:)

JBoss default password

I suggest visit Add digest auth in jmx-console and read oficial documentation for Configure admin consoles, you can add more security to your JBoss AS console and at these link explains where are the role and user/pass files that you need to change this information for your server and how you can change them. Also I recommend you quit all consoles that you don't use because they can affect to application server's performance. Also there are others links about securing jmx-console that could help you, search in jboss as community site for them (I can't put them here for my actual reputation,sorry). Never you should has the password in plain text over conf/props/ files.

Sorry for my bad English and I hope my answer be useful for you.

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

This should solve your problem:

td {
    /* <http://www.w3.org/wiki/CSS/Properties/text-align>
     * left, right, center, justify, inherit
     */
    text-align: center;
    /* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
     * baseline, sub, super, top, text-top, middle,
     * bottom, text-bottom, length, or a value in percentage
     */
    vertical-align: top;
}

How to return value from function which has Observable subscription inside?

This is not exactly correct idea of using Observable

In the component you have to declare class member which will hold an object (something you are going to use in your component)

export class MyComponent {
  name: string = "";
}

Then a Service will be returning you an Observable:

getValueFromObservable():Observable<string> {
    return this.store.map(res => res.json());
}

Component should prepare itself to be able to retrieve a value from it:

OnInit(){
  this.yourServiceName.getValueFromObservable()
    .subscribe(res => this.name = res.name)
}

You have to assign a value from an Observable to a variable:

And your template will be consuming variable name:

<div> {{ name }} </div>

Another way of using Observable is through async pipe http://briantroncone.com/?p=623

Note: If it's not what you are asking, please update your question with more details

Update Row if it Exists Else Insert Logic with Entity Framework

Alternative for @LadislavMrnka answer. This if for Entity Framework 6.2.0.

If you have a specific DbSet and an item that needs to be either updated or created:

var name = getNameFromService();

var current = _dbContext.Names.Find(name.BusinessSystemId, name.NameNo);
if (current == null)
{
    _dbContext.Names.Add(name);
}
else
{
    _dbContext.Entry(current).CurrentValues.SetValues(name);
}
_dbContext.SaveChanges();

However this can also be used for a generic DbSet with a single primary key or a composite primary key.

var allNames = NameApiService.GetAllNames();
GenericAddOrUpdate(allNames, "BusinessSystemId", "NameNo");

public virtual void GenericAddOrUpdate<T>(IEnumerable<T> values, params string[] keyValues) where T : class
{
    foreach (var value in values)
    {
        try
        {
            var keyList = new List<object>();

            //Get key values from T entity based on keyValues property
            foreach (var keyValue in keyValues)
            {
                var propertyInfo = value.GetType().GetProperty(keyValue);
                var propertyValue = propertyInfo.GetValue(value);
                keyList.Add(propertyValue);
            }

            GenericAddOrUpdateDbSet(keyList, value);
            //Only use this when debugging to catch save exceptions
            //_dbContext.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
    _dbContext.SaveChanges();
}

public virtual void GenericAddOrUpdateDbSet<T>(List<object> keyList, T value) where T : class
{
    //Get a DbSet of T type
    var someDbSet = Set(typeof(T));

    //Check if any value exists with the key values
    var current = someDbSet.Find(keyList.ToArray());
    if (current == null)
    {
        someDbSet.Add(value);
    }
    else
    {
        Entry(current).CurrentValues.SetValues(value);
    }
}

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

How can I style even and odd elements?

_x000D_
_x000D_
li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
_x000D_
<ul>_x000D_
  <li>list element 1</li>_x000D_
  <li>list element 2</li>_x000D_
  <li>list element 3</li>_x000D_
  <li>list element 4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

See browser support here : CSS3 :nth-child() Selector

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

Converting float to char*

char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

How can I change the default Django date template format?

If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:

{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}

Details for this tag here and more about dates according to the given format here

Example:

<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

As pointed out by @aarjithn, that WebP is a codec for storing photographs.

This is also a codec to store animations (animated image sequence). As of 2020, most mainstream browsers has out of the box support for it (compatibility table). Note for WIC a plugin is available.

It has advantages over GIF because it is based on a video codec VP8 and has a broader color range than GIF, where GIF limits to 256 colors it expands it to 224 = 16777216 colors, still saving significant amount of space.

How to emit an event from parent to child?

In a parent component you can use @ViewChild() to access child component's method/variable.

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponent: NumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }
} 

Update:

Angular 8 onwards -

@ViewChild(NumberComponent, { static: false })

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Best way to parseDouble with comma as decimal separator?

This is the static method I use in my own code:

public static double sGetDecimalStringAnyLocaleAsDouble (String value) {

    if (value == null) {
        Log.e("CORE", "Null value!");
        return 0.0;
    }

    Locale theLocale = Locale.getDefault();
    NumberFormat numberFormat = DecimalFormat.getInstance(theLocale);
    Number theNumber;
    try {
        theNumber = numberFormat.parse(value);
        return theNumber.doubleValue();
    } catch (ParseException e) {
        // The string value might be either 99.99 or 99,99, depending on Locale.
        // We can deal with this safely, by forcing to be a point for the decimal separator, and then using Double.valueOf ...
        //http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator
        String valueWithDot = value.replaceAll(",",".");

        try {
          return Double.valueOf(valueWithDot);
        } catch (NumberFormatException e2)  {
            // This happens if we're trying (say) to parse a string that isn't a number, as though it were a number!
            // If this happens, it should only be due to application logic problems.
            // In this case, the safest thing to do is return 0, having first fired-off a log warning.
            Log.w("CORE", "Warning: Value is not a number" + value);
            return 0.0;
        }
    }
}

File path issues in R using Windows ("Hex digits in character string" error)

replace all the \ with \\.

it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\

How to change a DIV padding without affecting the width/height ?

Declare this in your CSS and you should be good:

* { 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
     box-sizing: border-box; 
}

This solution can be implemented without using additional wrappers.

This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.

CSS endless rotation animation

Working nice:

_x000D_
_x000D_
#test {_x000D_
    width: 11px;_x000D_
    height: 14px;_x000D_
    background: url('data:image/gif;base64,R0lGOD lhCwAOAMQfAP////7+/vj4+Hh4eHd3d/v7+/Dw8HV1dfLy8ubm5vX19e3t7fr 6+nl5edra2nZ2dnx8fMHBwYODg/b29np6eujo6JGRkeHh4eTk5LCwsN3d3dfX 13Jycp2dnevr6////yH5BAEAAB8ALAAAAAALAA4AAAVq4NFw1DNAX/o9imAsB tKpxKRd1+YEWUoIiUoiEWEAApIDMLGoRCyWiKThenkwDgeGMiggDLEXQkDoTh CKNLpQDgjeAsY7MHgECgx8YR8oHwNHfwADBACGh4EDA4iGAYAEBAcQIg0Dk gcEIQA7');_x000D_
}_x000D_
_x000D_
@-webkit-keyframes rotating {_x000D_
    from{_x000D_
        -webkit-transform: rotate(0deg);_x000D_
    }_x000D_
    to{_x000D_
        -webkit-transform: rotate(360deg);_x000D_
    }_x000D_
}_x000D_
_x000D_
.rotating {_x000D_
    -webkit-animation: rotating 2s linear infinite;_x000D_
}
_x000D_
<div id='test' class='rotating'></div>
_x000D_
_x000D_
_x000D_

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

Graphical DIFF programs for linux

I have used Meld once, which seemed very nice, and I may try more often. vimdiff works well, if you know vim well. Lastly I would mention I've found xxdiff does a reasonable job for a quick comparison. There are many diff programs out there which do a good job.

With MySQL, how can I generate a column containing the record index in a table?

I know the OP is asking for a mysql answer but since I found the other answers not working for me,

  • Most of them fail with order by
  • Or they are simply very inefficient and make your query very slow for a fat table

So to save time for others like me, just index the row after retrieving them from database

example in PHP:

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1;
}

example in PHP using offset and limit for paging:

$limit = 20; //page size
$offset = 3; //page number

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1+($limit*($offset-1));
}

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Delete last commit in bitbucket

you can reset to HEAD^ then force push it.

git reset HEAD^
git push -u origin master --force

It will delete your last commit and will reflect on bitbucket as commit deleted but will still remain on their server.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

Select max value of each group

select name, value 
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1

How to execute a file within the python interpreter?

I'm trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Difference between == and ===

The difference between the loosely == equal operator and the strict === identical operator is exactly explained in the manual:

Comparison Operators

+----------------------------------------------------------------------------------+
¦ Example  ¦ Name      ¦ Result                                                    ¦
+----------+-----------+-----------------------------------------------------------¦
¦$a ==  $b ¦ Equal     ¦ TRUE if $a is equal to $b after type juggling.            ¦
¦$a === $b ¦ Identical ¦ TRUE if $a is equal to $b, and they are of the same type. ¦
+----------------------------------------------------------------------------------+

Loosely == equal comparison

If you are using the == operator, or any other comparison operator which uses loosely comparison such as !=, <> or ==, you always have to look at the context to see what, where and why something gets converted to understand what is going on.

Converting rules

Type comparison table

As reference and example you can see the comparison table in the manual:

Loose comparisons with ==

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ 1       ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ TRUE  ¦ TRUE  ¦
¦ -1      ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ array() ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

Strict === identical comparison

If you are using the === operator, or any other comparison operator which uses strict comparison such as !== or ===, then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.

Type comparison table

As reference and example you can see the comparison table in the manual:

Strict comparisons with ===

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 1       ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ -1      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ array() ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

How to "inverse match" with regex?

(?!Andrea).{6}

Assuming your regexp engine supports negative lookaheads..

Edit: ..or maybe you'd prefer to use [A-Za-z]{6} in place of .{6}

Edit (again): Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching, they leave that to whatever language you are using them with.

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

PHP header() redirect with POST variables

It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.

Edit:

If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

INSERT INTO vs SELECT INTO

  1. They do different things. Use INSERT when the table exists. Use SELECT INTO when it does not.

  2. Yes. INSERT with no table hints is normally logged. SELECT INTO is minimally logged assuming proper trace flags are set.

  3. In my experience SELECT INTO is most commonly used with intermediate data sets, like #temp tables, or to copy out an entire table like for a backup. INSERT INTO is used when you insert into an existing table with a known structure.

EDIT

To address your edit, they do different things. If you are making a table and want to define the structure use CREATE TABLE and INSERT. Example of an issue that can be created: You have a small table with a varchar field. The largest string in your table now is 12 bytes. Your real data set will need up to 200 bytes. If you do SELECT INTO from your small table to make a new one, the later INSERT will fail with a truncation error because your fields are too small.

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

How to find the index of an element in an array in Java?

For primitive arrays

Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.

Overloads can be added for int[], long[], etc. The body of the method will remain the same.

For Object arrays

For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.

But we can do it in a simpler manner with:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.

This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.

Create a view with ORDER BY clause

I've had success forcing the view to be ordered using

SELECT TOP 9999999 ... ORDER BY something

Unfortunately using SELECT TOP 100 PERCENT does not work due the issue here.

ng-options with simple array init

If you setup your select like the following:

<select ng-model="myselect" ng-options="b for b in options track by b"></select>

you will get:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

working fiddle: http://jsfiddle.net/x8kCZ/15/

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I'm a little late to this party, but I think I have something useful to add.

Kekoa's answer is great but, as RonLugge mentions, it can make the button no longer respect sizeToFit or, more importantly, can cause the button to clip its content when it is intrinsically sized. Yikes!

First, though,

A brief explanation of how I believe imageEdgeInsets and titleEdgeInsets work:

The docs for imageEdgeInsets have the following to say, in part:

Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge.

I believe that this documentation was written imagining that the button has no title, just an image. It makes a lot more sense thought of this way, and behaves how UIEdgeInsets usually do. Basically, the frame of the image (or the title, with titleEdgeInsets) is moved inwards for positive insets and outwards for negative insets.

OK, so what?

I'm getting there! Here's what you have by default, setting an image and a title (the button border is green just to show where it is):

Starting image; no space between title and image.

When you want spacing between an image and a title, without causing either to be crushed, you need to set four different insets, two on each of the image and title. That's because you don't want to change the sizes of those elements' frames, but just their positions. When you start thinking this way, the needed change to Kekoa's excellent category becomes clear:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
}

@end

But wait, you say, when I do that, I get this:

Spacing is good, but the image and title are outside the view's frame.

Oh yeah! I forgot, the docs warned me about this. They say, in part:

This property is used only for positioning the image during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.

But there is a property that can help, and that's contentEdgeInsets. The docs for that say, in part:

The button uses this property to determine intrinsicContentSize and sizeThatFits:.

That sounds good. So let's tweak the category once more:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
    self.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
}

@end

And what do you get?

Spacing and frame are now correct.

Looks like a winner to me.


Working in Swift and don't want to do any thinking at all? Here's the final version of the extension in Swift:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Android Service needs to run always (Never pause or stop)

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. In the manifest:

    android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

LINQ to Entities how to update a record

They both track your changes to the collection, just call the SaveChanges() method that should update the DB.

Undefined reference to main - collect2: ld returned 1 exit status

You can just add a main function to resolve this problem. Just like:

int main()
{
    return 0;
}

Splitting String and put it on int array

You are doing Integer division, so you will lose the correct length if the user happens to put in an odd number of inputs - that is one problem I noticed. Because of this, when I run the code with an input of '1,2,3,4,5,6,7' my last value is ignored...

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Anyone struggling to find where to set redirect urls in the new console: APIs & Auth -> Credentials -> OAuth 2.0 client IDs -> Click the link to find all your redirect urls

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How to dynamically add a class to manual class names?

try this using hooks:

const [dynamicClasses, setDynamicClasses] = React.useState([
    "dynamicClass1", "dynamicClass2"
]);

and add this in className attribute :

<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>

to add class :

    const addClass = newClass => {
       setDynamicClasses([...dynamicClasses, newClass])
    }

to delete class :

        const deleteClass= classToDelete => {

           setDynamicClasses(dynamicClasses.filter(class = > {
             class !== classToDelete
           }));

        }

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Android Studio gradle takes too long to build

Check disk usage in Windows OS ...

The problem can be related to this, in my case I had Windows 8 OS consuming a 100% disk usage.

Especially the Windows Search service, can be the most consuming. Disable it with:

cmd (Admin)

net.exe stop "Windows search"

Check this link 4 Tips to Fix 100% Disk Usage & Improve Windows Performance

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

Change Default branch in gitlab

To change the default branch in Gitlab 7.7.2:

  • Click Settings in the left-hand bar
  • Change the Default Branch to the desired branch
  • Click Save Changes.

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Convert XML to JSON (and back) using Javascript

I think this is the best one: Converting between XML and JSON

Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

alter table MYTABLE modify (MYCOLUMN null);

In Oracle, not null constraints are created automatically when not null is specified for a column. Likewise, they are dropped automatically when the column is changed to allow nulls.

Clarifying the revised question: This solution only applies to constraints created for "not null" columns. If you specify "Primary Key" or a check constraint in the column definition without naming it, you'll end up with a system-generated name for the constraint (and the index, for the primary key). In those cases, you'd need to know the name to drop it. The best advice there is to avoid the scenario by making sure you specify a name for all constraints other than "not null". If you find yourself in the situation where you need to drop one of these constraints generically, you'll probably need to resort to PL/SQL and the data-definition tables.

Adding <script> to WordPress in <head> element

Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.

In your functions.php file, add

$inject_required_scripts = array();

/**
 * Call this function before calling get_header() to request custom js code to be injected on head.
 *
 * @param code the javascript code to be injected.
 */
function require_script($code) {
  global $inject_required_scripts;
  $inject_required_scripts[] = $code; // store code snippet for later injection
}

function inject_required_scripts() {
  global $inject_required_scripts;
  foreach($inject_required_scripts as $script)
    // inject all code snippets, if any
    echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');

And then in your page or template, use it like

<?php
/* Template Name: coolstuff */

require_script(<<<JS
  jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);

require_script(<<<JS
  jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);

get_header();
[...]

I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

How to replace local branch with remote branch entirely in Git?

I'm kind of surprised no one mentioned this yet; I use it nearly every day:

git reset --hard @{u}

Basically, @{u} is just shorthand for the upstream branch that your current branch is tracking. For example, this typically equates to origin/[my-current-branch-name]. It's nice because it's branch agnostic.

Make sure to git fetch first to get the latest copy of the remote branch.

Any tools to generate an XSD schema from an XML instance document?

There also is XML schema learner which is available on Github.

It can take multiple xml files and extract a common XSD from all of those files.

Error: Could not find or load main class

If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.

Can't get value of input type="file"?

You can't set the value of a file input in the markup, like you did with value="123".

This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/

How to make an "alias" for a long path?

Maybe it's better to use links

Soft Link

Symbolic or soft link (files or directories, more flexible and self documenting)

#      Source                            Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard Link

Hard link (files only, less flexible and not self documenting)

#    Source                            Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

How to create a link to a directory

Hint: If you need not to see the link in your home you can start it with a dot . ; then it will be hidden by default then you can access it like

cd ~/.myHiddelLongDirLink

Cannot checkout, file is unmerged

Following is worked for me

git reset HEAD

I was getting following error

git stash
src/config.php: needs merge
src/config.php: needs merge
src/config.php: unmerge(230a02b5bf1c6eab8adce2cec8d573822d21241d)
src/config.php: unmerged (f5cc88c0fda69bf72107bcc5c2860c3e5eb978fa)

Then i ran

git reset HEAD

it worked

How do I catch an Ajax query post error?

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

Plotting images side by side using matplotlib

As per matplotlib's suggestion for image grids:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

What is the Eclipse shortcut for "public static void main(String args[])"?

Type main and press and hold Ctrl and next press Space Space (double space) and select, it or pressenter to focus on main option.

This is fastest way.

Make a div fill up the remaining width

I was looking for a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side, so I came up with the following and thought I'd post it here in case anyone needs it.

_x000D_
_x000D_
#wrapper {_x000D_
  clear: both;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
  display: inline-block;_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
#center {_x000D_
  background-color: green;_x000D_
  margin: 0 auto;_x000D_
  overflow: auto;_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.fluid {_x000D_
  background-color: yellow;_x000D_
  width: calc(50% - 250px);_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="center">_x000D_
    This is fixed width in the centre_x000D_
  </div>_x000D_
  <div id="left" class="fluid">_x000D_
    This is fluid width on the left_x000D_
  </div>_x000D_
  <div id="right" class="fluid">_x000D_
    This is fluid width on the right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you change the width of the #center element then you need to update the width property of .fluid to:

width: calc(50% - [half of center width]px);

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb

Possible Issues
 \\ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb; 
      ...`

I found that the simplest is to do the below - I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

How to parse JSON response from Alamofire API in Swift?

This was build with Xcode 10.1 and Swift 4

Perfect combination "Alamofire"(4.8.1) and "SwiftyJSON"(4.2.0). First you should install both pods

pod 'Alamofire' and pod 'SwiftyJSON'

The server response in JSON format:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", 
    "Accept-Language": "en;q=1.0", 
    "Host": "httpbin.org", 
    "User-Agent": "AlamoFire TEST/1.0 (com.ighost.AlamoFire-TEST; build:1; iOS 12.1.0) Alamofire/4.8.1"
  }, 
  "origin": "200.55.140.181, 200.55.140.181", 
  "url": "https://httpbin.org/get"
}

In this case I want print the "Host" info : "Host": "httpbin.org"

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
        switch response.result {
        case .success:
            print("Validation Successful)")

            if let json = response.data {
                do{
                    let data = try JSON(data: json)
                    let str = data["headers"]["Host"]
                    print("DATA PARSED: \(str)")
                }
                catch{
                print("JSON Error")
                }

            }
        case .failure(let error):
            print(error)
        }
    }

Keep Calm and happy Code

Python decorators in classes

I have a Implementation of Decorators that Might Help

    import functools
    import datetime


    class Decorator(object):

        def __init__(self):
            pass


        def execution_time(func):

            @functools.wraps(func)
            def wrap(self, *args, **kwargs):

                """ Wrapper Function """

                start = datetime.datetime.now()
                Tem = func(self, *args, **kwargs)
                end = datetime.datetime.now()
                print("Exection Time:{}".format(end-start))
                return Tem

            return wrap


    class Test(Decorator):

        def __init__(self):
            self._MethodName = Test.funca.__name__

        @Decorator.execution_time
        def funca(self):
            print("Running Function : {}".format(self._MethodName))
            return True


    if __name__ == "__main__":
        obj = Test()
        data = obj.funca()
        print(data)

Trying to get Laravel 5 email to work

If you ever have the same trouble and try everything online and it doesn't work, it is probably the config cache file that is sending the wrong information. You can find it in bootstrap/cache/config.php. Make sure the credentials are right in there. It took me a week to figure that out. I hope this will help someone someday.

How to set Apache Spark Executor memory

You need to increase the driver memory.On mac(i.e when running on local master), the default driver-memory is 1024M). By default, thus 380Mb is allotted to the executor.

Screenshot

Upon increasing [--driver-memory 2G], executor memory got increased to ~950Mb. enter image description here

iOS: Modal ViewController with transparent background

This code works fine on iPhone under iOS6 and iOS7:

presentedVC.view.backgroundColor = YOUR_COLOR; // can be with 'alpha'
presentingVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[presentingVC presentViewController:presentedVC animated:YES completion:NULL];

In this case you miss slide-on animation. To retain animation you still can use the following "non-elegant" extension:

[presentingVC presentViewController:presentedVC animated:YES completion:^{
    [presentedVC dismissViewControllerAnimated:NO completion:^{
        presentingVC.modalPresentationStyle = UIModalPresentationCurrentContext;
        [presentingVC presentViewController:presentedVC animated:NO completion:NULL];
    }];
}];

If our presentingV is located inside of UINavigationController or UITabbarController you need to operate with that controllers as presentingVC.

Further, in iOS7 you can implement custom transition animation applying UIViewControllerTransitioningDelegate protocol. Of course, in this case you can get transparent background

@interface ModalViewController : UIViewController <UIViewControllerTransitioningDelegate>

First, before presenting you have to set modalPresentationStyle

modalViewController.modalPresentationStyle = UIModalPresentationCustom;

Then you have to implement two protocol methods

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    CustomAnimatedTransitioning *transitioning = [CustomAnimatedTransitioning new];
    transitioning.presenting = YES;
    return transitioning;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    CustomAnimatedTransitioning * transitioning = [CustomAnimatedTransitioning new];
    transitioning.presenting = NO;
    return transitioning;
}

The last thing is to define your custom transition in CustomAnimatedTransitioning class

@interface CustomAnimatedTransitioning : NSObject <UIViewControllerAnimatedTransitioning>
@property (nonatomic) BOOL presenting;
@end

@implementation CurrentContextTransitionAnimator

- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext 
{
    return 0.25;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext 
{
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    if (self.presenting) {
        // custom presenting animation
    }
    else {
        // custom dismissing animation
    }
}

Can I call methods in constructor in Java?

You can. But by placing this in the constructor you are making your object hard to test.

Instead you should:

  • provide the configuration with a setter
  • have a separate init() method

Dependency injection frameworks give you these options.

public class ConfigurableObject {
   private Map<String, String> configuration;
   public ConfigurableObject() {

   }

   public void setConfiguration(..) {
       //...simply set the configuration
   }
}

An example of the 2nd option (best used when the object is managed by a container):

public class ConfigurableObject {
   private File configFile;
   private Map<String, String> configuration;
   public ConfigurableObject(File configFile) {
       this.configFile = configFile;
   }

   public void init() {
       this.configuration = parseConfig(); // implement
   }
}

This, of course, can be written by just having the constructor

public ConfigurableObject(File configfile) {
    this.configuration = parseConfig(configFile);
}

But then you won't be able to provide mock configurations.

I know the 2nd opttion sounds more verbose and prone to error (if you forget to initialize). And it won't really hurt you that much if you do it in a constructor. But making your code more dependency-injection oriented is generally a good practice.

The 1st option is best - it can be used with both DI framework and with manual DI.

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

How to install Android SDK on Ubuntu?

Option 1:

sudo apt update && sudo apt install android-sdk

The location of Android SDK on Linux can be any of the following:

  • /home/AccountName/Android/Sdk

  • /usr/lib/android-sdk

  • /Library/Android/sdk/

  • /Users/[USER]/Library/Android/sdk

Option 2:

  • Download the Android Studio.

  • Extract downloaded .zip file.

    The extracted folder name will read somewhat like android-studio

To keep navigation easy, move this folder to Home directory.

  • After moving, copy the moved folder by right clicking it. This action will place folder's location to clipboard.

  • Use Ctrl Alt T to open a terminal

  • Go to this folder's directory using cd /home/(USER NAME)/android-studio/bin/

  • Type this command to make studio.sh executable: chmod +x studio.sh

  • Type ./studio.sh

A pop up will be shown asking for installation settings. In my particular case, it is a fresh install so I'll go with selecting I do not have a previous version of Studio or I do not want to import my settings.

If you choose to import settings anyway, you may need to close any old project which is opened in order to get a working Android SDK.

./studio.sh popup

From now onwards, setup wizard will guide you.

Android studio setup wizard

Android Studio can work with both Open JDK and Oracle's JDK (recommended). Incase, Open JDK is installed the wizard will recommend installing Oracle Java JDK because some UI and performance issues are reported while using OpenJDK.

The downside with Oracle's JDK is that it won't update with the rest of your system like OpenJDK will.

The wizard may also prompt about the input problems with IDEA .

Select install type

Select Android studio install type

Verify installation settings

Verify Android studio installation settings

An emulator can also be configured as needed.

Android studio emulator configuration prompt

The wizard will start downloading the necessary SDK tools

The wizard may also show an error about Linux 32 Bit Libraries, which can be solved by using the below command:

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

After this, all the required components will be downloaded and installed automatically.

After everything is upto the mark, just click finish

Completed installation of Android studio

To make a Desktop icon, go to 'Configure' and then click 'Create Desktop Entry'

Creating Android studio desktop icon

Creating Android studio desktop icon for one or multiple users

source

Prevent screen rotation on Android

Add:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        ...
        ...
        ...
}

Getting a map() to return a list in Python 3.x

list(map(chr, [66, 53, 0, 94]))

map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

"Make an iterator"

means it will return an iterator.

"that computes the function using arguments from each of the iterables"

means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.

So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.

How do I create delegates in Objective-C?

I think all these answers make a lot of sense once you understand delegates. Personally I came from the land of C/C++ and before that procedural languages like Fortran etc so here is my 2 min take on finding similar analogues in C++ paradigm.

If I were to explain delegates to a C++/Java programmer I would say

What are delegates ? These are static pointers to classes within another class. Once you assign a pointer, you can call functions/methods in that class. Hence some functions of your class are "delegated" (In C++ world - pointer to by a class object pointer) to another class.

What are protocols ? Conceptually it serves as similar purpose as to the header file of the class you are assigning as a delegate class. A protocol is a explicit way of defining what methods needs to be implemented in the class who's pointer was set as a delegate within a class.

How can I do something similar in C++? If you tried to do this in C++, you would by defining pointers to classes (objects) in the class definition and then wiring them up to other classes that will provide additional functions as delegates to your base class. But this wiring needs to be maitained within the code and will be clumsy and error prone. Objective C just assumes that programmers are not best at maintaining this decipline and provides compiler restrictions to enforce a clean implementation.

I want to convert std::string into a const wchar_t *

If you have a std::wstring object, you can call c_str() on it to get a wchar_t*:

std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();

Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar routine. That will give you an LPWSTR, which is equivalent to wchar_t*.

How to check if running as root in a bash script

Check if you are root and quit if you are not:

if ((EUID != 0)); then
    echo "Root or Sudo  Required for script ( $(basename $0) )"
    exit
fi

Or in this example, try to create a directory in root location then try after rights were elevated.

Check if you are root and if not elevate if possible :

# Fails to create these dirs (needs sudo)
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)

if ((EUID != 0)); then
    echo "Granting root privileges for script ( $(basename $0) )"
    if [[ -t 1 ]]; then
        sudo "$0" "$@"
    else
        exec 1> output_file
        gksu "$0" "$@"
    fi
    exit
fi
echo "Root privileges granted..."
# Creates Dirs as it now has rights
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I also got the same running java JDBC in NetBeans. This is how it fixed

I use Xampp. In conf button of Apache I opened httpd.conf file and on first line I typed

# Set timezone to Europe/Athens UTC+02:00 
SetEnv TZ Europe/Athens.

In conf button of MySQL I opened my.ini file and on last line I typed "Europe/Athens"

Stopped and started both Apache and MySQL

Problem fixed.

*(Local mechine time zone is different, but no problem.)

how to do "press enter to exit" in batch

Use this snippet:

@echo off
echo something
echo.
echo press enter to exit
pause >nul
exit

Check array position for null/empty

If your array is not initialized then it contains randoms values and cannot be checked !

To initialize your array with 0 values:

int array[5] = {0};

Then you can check if the value is 0:

array[4] == 0;

When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.

If you have an array of pointers, better use the nullptr value to check:

char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr

if (array[4] == nullptr)
    // do something

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

How to tell if UIViewController's view is visible

For my purposes, in the context of a container view controller, I've found that

- (BOOL)isVisible {
    return (self.isViewLoaded && self.view.window && self.parentViewController != nil);
}

works well.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.

How do I create an average from a Ruby array?

You can choose one of the below solutions as you wish.

Bruteforce

[0,4,8,2,5,0,2,6].sum.to_f / [0,4,8,2,5,0,2,6].size.to_f

=> 3.375

Method

def avg(array)
  array.sum.to_f / array.size.to_f
end  

avg([0,4,8,2,5,0,2,6])
=> 3.375

Monkey Patching

class Array
  def avg
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].avg
=> 3.375

But I don't recommend to monkey patch the Array class, this practice is dangerous and can potentially lead to undesirable effects on your system.

For our good, ruby language provides a nice feature to overcome this problem, the Refinements, which is a safe way for monkey patching on ruby.

To simplify, with the Refinements you can monkey patch the Array class and the changes will only be available inside the scope of the class that is using the refinement! :)

You can use the refinement inside the class you are working on and you are ready to go.

Refinements

module ArrayRefinements
  refine Array do
    def avg
      sum.to_f / size.to_f
    end
  end
end

class MyClass
  using ArrayRefinements

  def test(array)
    array.avg
  end
end

MyClass.new.test([0,4,8,2,5,0,2,6])
=> 3.375

How to center the text in PHPExcel merged cell

We can also set the vertical alignment with using this way

$style_cell = array(
   'alignment' => array(
       'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
       'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
   ) 
); 

with this cell set the vertically aligned into the middle.

How can I get a JavaScript stack trace when I throw an exception?

Wow - I don't see a single person in 6 years suggesting that we check first to see if stack is available before using it! The worst thing you can do in an error handler is throw an error because of calling something that doesn't exist.

As others have said, while stack is mostly safe to use now it is not supported in IE9 or earlier.

I log my unexpected errors and a stack trace is pretty essential. For maximum support I first check to see if Error.prototype.stack exists and is a function. If so then it is safe to use error.stack.

        window.onerror = function (message: string, filename?: string, line?: number, 
                                   col?: number, error?: Error)
        {
            // always wrap error handling in a try catch
            try 
            {
                // get the stack trace, and if not supported make our own the best we can
                var msg = (typeof Error.prototype.stack == 'function') ? error.stack : 
                          "NO-STACK " + filename + ' ' + line + ':' + col + ' + message;

                // log errors here or whatever you're planning on doing
                alert(msg);
            }
            catch (err)
            {

            }
        };

Edit: It appears that since stack is a property and not a method you can safely call it even on older browsers. I'm still confused because I was pretty sure checking Error.prototype worked for me previously and now it doesn't - so I'm not sure what's going on.