Programs & Examples On #Data recovery

DO NOT USE THIS TAG if your question is about recovering data you lost on your device. Only use this tag for programming issues related to data recovery. Data recovery is a process of salvaging inaccessible data from corrupted or damaged storage when the data cannot be accessed in a normal way.

Where does MySQL store database files on Windows and what are the names of the files?

MYSQL 8.0:

Search my.ini in disk, we will find this folder:

C:\ProgramData\MySQL\MySQL Server 8.0
It's ProgramData, not Program file

Data is in sub-folder: \Data.

Each database owns a folder, each table is file, each index is 1+ files.

Here is a sample database sakila: enter image description here

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.


(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.


You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals


See my blog entry Preventing PostgreSQL database corruption.

On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How to recover Git objects damaged by hard disk failure?

Git checkout can actually pick out individual files from a revision. Just give it the commit hash and the file name. More detailed info here.

I guess the easiest way to fix this safely is to revert to the newest uncommited backup and then selectively pick out uncorrupted files from newer commits. Good luck!

How do I view events fired on an element in Chrome DevTools?

You can use monitorEvents function.

Just inspect your element (right mouse click ? Inspect on visible element or go to Elements tab in Chrome Developer Tools and select wanted element) then go to Console tab and write:


Now when you move mouse over this element, focus or click it, the name of the fired event will be displayed with its data.

To stop getting this data just write this to console:


$0 is just the last DOM element selected by Chrome Developer Tools. You can pass any other DOM object there (for example result of getElementById or querySelector).

You can also specify event "type" as second parameter to narrow monitored events to some predefined set. For example:

monitorEvents(document.body, 'mouse')

List of this available types is here.

I made a small gif that illustrates how this feature works:

usage of monitorEvents function

How to wrap text using CSS?

This will work everywhere.

  <table style="table-layout:fixed;">
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>

How to position background image in bottom right corner? (CSS)

This should do it:

body {
    background:url(bg.jpg) fixed no-repeat bottom right;

sql use statement with variable

The problem with the former is that what you're doing is USE 'myDB' rather than USE myDB. you're passing a string; but USE is looking for an explicit reference.

The latter example works for me.

declare @sql varchar(20)
select @sql = 'USE myDb'
EXEC sp_sqlexec @Sql

-- also works
select @sql = 'USE [myDb]'
EXEC sp_sqlexec @Sql

Finding the direction of scrolling in a UIScrollView?

Swift 4:

For the horizontal scrolling you can simply do :

if scrollView.panGestureRecognizer.translation(in: scrollView.superview).x > 0 {
} else {

For vertical scrolling change .x with .y

Creating email templates with Django

I like using this tool to permit easily to send email HTML and TXT with easy context processing:

Style the first <td> column of a table differently

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.

For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

td:nth-child(3n+1) {  
  /* your stuff here */

:nth-of-type() works the same, except that it only considers element of the given type ( in the example).

How to iterate over the files of a certain directory, in Java?

If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

How do I make an auto increment integer field in Django?

You can create an autofield. Here is the documentation for the same

Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.

Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Template not provided using create-react-app

After using this command:

yarn global upgrade create-react-app

I then tried:

yarn create-react-app my-app but it didn't work for me.

This worked though:

npx create-react-app my-app 

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

return str.replace(/\s/g, '');

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

Set Page Title using PHP

What about using something like:

    $page_title = "Your page tile";
    include("navigation.php");             // if required

How to parse/format dates with LocalDateTime? (Java 8)


// Current UTC time
        OffsetDateTime utc =;

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

How do I fix MSB3073 error in my post-build event?

The specified error is related to the post built event. Somehow VS tool is not able to copy the files to the destination folder. There can be many reasons for it. To check the exact error cause go to Tools > Option> Project and Solution > Built and run, and change "MsBuild project build output verbosity" to "Diagnostic". It will give you enough information to detect the actual problem.

Static vs class functions/variables in Swift classes?

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.

Check whether number is even or odd

package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
    public static void main(String[] args) {
        Scanner scan = new Scanner(;
        System.out.println("Enter number: ");
        int y = scan.nextInt();       
        boolean isEven = (y % 2 == 0) ? true : false;
        String x = (isEven) ? "even" : "odd";  
        System.out.println("Your number is " + x);

Convert date from String to Date format in Dataframes

Since your main aim was to convert the type of a column in a DataFrame from String to Timestamp, I think this approach would be better.

import org.apache.spark.sql.functions.{to_date, to_timestamp}
val modifiedDF = DF.withColumn("Date", to_date($"Date", "MM/dd/yyyy"))

You could also use to_timestamp (I think this is available from Spark 2.x) if you require fine grained timestamp.

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code

Best Practices for securing a REST API / web service

There is a great checklist found on Github:


  • Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.

  • Use Max Retry and jail features in Login.

  • Use encryption on all sensitive data.

JWT (JSON Web Token)

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.

  • Don't extract the algorithm from the payload. Force the algorithm in the backend (HS256 or RS256).

  • Make token expiration (TTL, RTTL) as short as possible.

  • Don't store sensitive data in the JWT payload, it can be decoded easily.


  • Always validate redirect_uri server-side to allow only whitelisted URLs.

  • Always try to exchange for code and not tokens (don't allow response_type=token).

  • Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.

  • Define the default scope, and validate scope parameters for each application.


  • Limit requests (Throttling) to avoid DDoS / brute-force attacks.

  • Use HTTPS on server side to avoid MITM (Man In The Middle Attack)

  • Use HSTS header with SSL to avoid SSL Strip attack.


  • Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.

  • Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc) and respond with 406 Not Acceptable response if not matched.

  • Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc).

  • Validate User input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc).

  • Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.

  • Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, Concurrent Rate Limit) and deploy APIs resources dynamically.


  • Check if all the endpoints are protected behind authentication to avoid broken authentication process.

  • User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.

  • Don't auto-increment IDs. Use UUID instead.

  • If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).

  • If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.

  • Use a CDN for file uploads.

  • If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.

  • Do not forget to turn the DEBUG mode OFF.


  • Send X-Content-Type-Options: nosniff header.

  • Send X-Frame-Options: deny header.

  • Send Content-Security-Policy: default-src 'none' header.

  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.

  • Force content-type for your response, if you return application/json then your response content-type is application/json.

  • Don't return sensitive data like credentials, Passwords, security tokens.

  • Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).

How to get the difference between two dictionaries in Python?

What about this? Not as pretty but explicit.

orig_dict = {'a' : 1, 'b' : 2}
new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}

updates = {}
for k2, v2 in new_dict.items():
    if k2 in orig_dict:    
        if v2 != orig_dict[k2]:
            updates.update({k2 : v2})
        updates.update({k2 : v2})

#test it
#value of 'a' was changed
#'v' is a completely new entry
assert all(k in updates for k in ['a', 'v'])

Remove all multiple spaces in Javascript and replace with single space

you all forget about quantifier n{X,}

here best solution

str = str.replace(/\s{2,}/g, ' ');

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

It can also happen due to a typo in referencing a table such as [dbo.Product] instead of [dbo].[Product].

Installing J2EE into existing eclipse IDE

For Mars (Eclipse 4.5) and WTP 3.7 use this link.

  1. In Eclipse select Help - Install New Software.
  2. In the "Work with:" text box place the above link.
  3. Press Enter.
  4. Select the WTP version you need (3.7.0 or 3.7.1 as of today) & follow the prompts.

Firebase: how to generate a unique numeric ID for key?

Adding to the @htafoya answer. The code snippet will be

const getTimeEpoch = () => {
    return new Date().getTime().toString();                             

Unable to connect PostgreSQL to remote database using pgAdmin

Check your firewall. When you disable it, then you can connect. If you want/can't disable the firewall, add a rule for your remote connection.

Returning null in a method whose signature says return int?

The type int is a primitive and it cannot be null, if you want to return null, mark the signature as

public Integer pollDecrementHigherKey(int x) {
    x = 10;

    if (condition) {
        return x; // This is auto-boxing, x will be automatically converted to Integer
    } else if (condition2) {
        return null; // Integer inherits from Object, so it's valid to return null
    } else {
        return new Integer(x); // Create an Integer from the int and then return
    return 5; // Also will be autoboxed and converted into Integer

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()

output: 3

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

iPhone 5 CSS media query

None of the response works for me targeting a phonegapp App.

As the following link points, the solution below works.

@media screen and (device-height: 568px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
    // css here

Call break in nested if statements

In the most languages, break does only cancel loops like for, while etc.

Excel: the Incredible Shrinking and Expanding Controls

I had the problem also with ActiveX listboxes and found the following elsewhere and it seems to work so far, and it seems also the by far easiest solution that transfer along when handing the spreadsheet to someone else:

"While the ListBox has an IntegralHeight property whose side-effect of a FALSE setting will keep that control from going askew, and while command buttons have properties such as move/size with cells, etc., other controls are not as graceful."

And they have some more advice:

Scheduling recurring task in Android

I realize this is an old question and has been answered but this could help someone. In your activity

private ScheduledExecutorService scheduleTaskExecutor;

In onCreate

  scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run every 5 seconds (or however long you want)
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();

    }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.

Can you target an elements parent element using

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener will be the clicked element, the <section> will be in event.currentTarget.

Otherwise parentNode might be what you're looking for.

link to currentTarget
link to parentNode

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("", headers={"content-type":"text"})

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?


below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!

To undo make install I would do (and I did) this:

Idea: check whatever script installs and undo this with simple bash script.

  1. Reconfigure your build dir to install to some custom dir. I usually do this: --prefix=$PWD/install. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.
  2. Install project to custom directory (just run make install again).
  3. Now we push from assumption, that make install script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local). So, we need a script. 3.1. Script should compare custom dir, with dir you want clean. I use this:


echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"

pushd $RM_DIR

for fn in `find . -iname '*'`; do
#  echo "Checking $PRESENT_DIR/$fn..."
  if test -f "$PRESENT_DIR/$fn"; then
    # First try this, and check whether things go plain
    echo "rm $RM_DIR/$fn"

    # Then uncomment this, (but, check twice it works good to you).
    # rm $RM_DIR/$fn


3.2. Now just run this script (it will go dry-run)

bash <dir you want to clean> <custom installation dir>

E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/, then it would be

bash /usr/local /user/me/

3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn and run it again. But stop! Did you really check carefully? May be check again?

Source to instructions:

Good luck!

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

This worked for me after struggling a bit




How do I set specific environment variables when debugging in Visual Studio?

You can set it at Property > Configuration Properties > Debugging > Environment enter image description here

How to force garbage collection in Java?

I would like to add some thing here. Please not that Java runs on Virtual Machine and not actual Machine. The virtual machine has its own way of communication with the machine. It may varry from system to system. Now When we call the GC we ask the Virtual Machine of Java to call the Garbage Collector.

Since the Garbage Collector is with Virtual Machine , we can not force it to do a cleanup there and then. Rather that we queue our request with the Garbage Collector. It depends on the Virtual Machine, after particular time (this may change from system to system, generally when the threshold memory allocated to the JVM is full) the actual machine will free up the space. :D

how to call url of any other website in php

As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents to access REST APIs:

$payload = file_get_contents('');

Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.

How to set an environment variable from a Gradle build?

In case you're using Gradle Kotlin syntax, you also can do:

tasks.taskName {
    environment(mapOf("A" to 1, "B" to "C"))

So for test task this would be:

tasks.test {
    environment(mapOf("SOME_TEST_VAR" to "aaa"))

How to generate a range of numbers between two numbers?

Here are couple quite optimal and compatible solutions:

USE master;

declare @min as int;    set @min = 1000;
declare @max as int;    set @max = 1050;    --null returns all

--  Up to 256 - 2 048 rows depending on SQL Server version
select  isnull(@min,0)+number.number  as  number
FROM    dbo.spt_values  AS  number
WHERE   number."type"                   =   'P'     --integers
    and (   @max                            is null     --return all
        or  isnull(@min,0)+number.number    <=  @max    --return up to max
order by    number

--  Up to 65 536 - 4 194 303 rows depending on SQL Server version
select  isnull(@min,0)+value1.number+(value2.number*numberCount.numbers)  as  number
FROM  dbo.spt_values            AS  value1
  cross join  dbo.spt_values    AS  value2
  cross join (  --get the number of numbers (depends on version)
    select  sum(1)  as  numbers
    from    dbo.spt_values
    where   spt_values."type"   =   'P' --integers
  )                             as  numberCount
WHERE   value1."type" = 'P'   --integers
    and value2."type" = 'P'   --integers
    and (   @max    is null     --return all
        or  isnull(@min,0)+value1.number+(value2.number*numberCount.numbers)    
            <=  @max            --return up to max
order by    number

PHP - regex to allow letters and numbers only

1. Use PHP's inbuilt ctype_alnum

You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster:

$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";

2. Alternatively, use a regex

If you desperately want to use a regex, you have a few options.


preg_match('/^[\w]+$/', $string);

\w includes more than alphanumeric (it includes underscore), but includes all of \d.



Or even just:


Error: Cannot Start Container: stat /bin/sh: no such file or directory"

After you create image, check it with:

$ docker inspect $image_name 

and check what you have in CMD option. For busy box it should be:

"Cmd": [

Maybe you are overwritting CMD option in your ./

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.

Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

Iterate through a HashMap

Depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().

A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE AND table2.item=table1.item);

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;

Just did it now for a client, and it seems to be working:

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:


$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");

How to remove elements/nodes from angular.js array

I liked the solution provided by @madhead

However the problem I had is that it wouldn't work for a sorted list so instead of passing the index to the delete function I passed the item and then got the index via indexof


var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);

An updated version of madheads example is below: link to example


<!DOCTYPE html>
<html data-ng-app="demo">
    <script data-require="[email protected]" data-semver="1.1.5" src=""></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <div data-ng-controller="DemoController">
        <li data-ng-repeat="item in items|orderBy:'toString()'">
          <button data-ng-click="removeItem(item)">Remove</button>
      <input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>


"use strict";

var demo = angular.module("demo", []);

function DemoController($scope){
  $scope.items = [

  $scope.addItem = function(item){
    $scope.newItem = null;

  $scope.removeItem = function(item){
    var index = $scope.items.indexOf(item);
    $scope.items.splice(index, 1);

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here:

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Personally, I found that, since we maintain a ngRoutes collection (long story) i find the most enjoyment from:

GOTO(ri) {

I actually use it as part of one of our interview questions. This way, I can get a near-instant read at who's been developing forever by watching who twitches when they run into GOTO(1) for Homepage redirection.

setImmediate vs. nextTick

In the comments in the answer, it does not explicitly state that nextTick shifted from Macrosemantics to Microsemantics.

before node 0.9 (when setImmediate was introduced), nextTick operated at the start of the next callstack.

since node 0.9, nextTick operates at the end of the existing callstack, whereas setImmediate is at the start of the next callstack

check out for tools and details

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then


If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then


Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Using Mockito to test abstract classes

class Dependency{
  public void method(){};

public abstract class My {

  private Dependency dependency;
  public abstract boolean myAbstractMethod();

  public void myNonAbstractMethod() {
    // ...

public class MyTest {

  private My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
  // we can mock dependencies also here
  private Dependency dependency;

  private void shouldPass() {
    // can be mock the dependency object here.
    // It will be useful to test non abstract method

How to display image from URL on Android

Write the code using ASyncTask for http handling.

Bitmap b;
ImageView img;
        URL url = new URL("");
        InputStream is = new BufferedInputStream(url.openStream());
        b = BitmapFactory.decodeStream(is);
    } catch(Exception e){}

In Python, when to use a Dictionary, List or Set?

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.

Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.

Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.

Understanding the Gemfile.lock file

Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem).

Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically.

Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency.

When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation.

Same happens when you share your code with different machines

You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines

Why do we need to maintain consistency along multiple machines ?

  • Running different versions on different machines could lead to broken code

  • Suppose, your app used the version 1.5.3 and it works 14 months ago
    without any problems, and you try to install on different machine
    without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will
    fail. Maintaining consistency is of utmost importance (preferred

It is also possible to update gem(s) in Gemfile.lock by using bundle update.

This is based on the concept of conservative updating

Android LinearLayout : Add border with shadow around a LinearLayout

Use this single line and hopefully you will achieve the best result;

use: android:elevation="3dp" Adjust the size as much as you need and this is the best and simplest way to achieve the shadow like buttons and other default android shadows. Let me know if it worked!

Toggle visibility property of div

Using jQuery:

  if ( $('#video-over').css('visibility') == 'hidden' )

Insert using LEFT JOIN and INNER JOIN

INSERT INTO Test([col1],[col2]) (
        a.Name AS [col1],
        b.sub AS [col2] 
    FROM IdTable b 
    INNER JOIN Nametable a ON =

CSS position absolute full width problem

Make #site_nav_global_primary positioned as fixed and set width to 100 % and desired height.

Getting json body in aws Lambda via API gateway

You may have forgotten to define the Content-Type header. For example:

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    body: JSON.stringify({ items }),

How do I use TensorFlow GPU?

Uninstall tensorflow and install only tensorflow-gpu; this should be sufficient. By default, this should run on the GPU and not the CPU. However, further you can do the following to specify which GPU you want it to run on.

If you have an nvidia GPU, find out your GPU id using the command nvidia-smi on the terminal. After that, add these lines in your script:

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = #GPU_ID from earlier

config = tf.ConfigProto()
sess = tf.Session(config=config)

For the functions where you wish to use GPUs, write something like the following:

with tf.device(tf.DeviceSpec(device_type="GPU", device_index=gpu_id)):

Most efficient way to create a zero filled JavaScript array?

What everyone else seems to be missing is setting the length of the array beforehand so that the interpreter isn't constantly changing the size of the array.

My simple one-liner would be Array.prototype.slice.apply(new Uint8Array(length))

But if I were to create a function to do it fast without some hacky workaround, I would probably write a function like this:

var filledArray = function(value, l) {
    var i = 0, a = []; a.length = l;
    while(i<l) a[i++] = value;
    return a;

How to change Screen buffer size in Windows Command Prompt from batch script

I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!

mode con:cols=140 lines=70

The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.

Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.

My batch script ends up looking like this:

@echo off
cmd "mode con:cols=140 lines=2500"

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

What is sharding and why is it important?

Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.

Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)

PowerShell equivalent to grep -f

PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe

105:-a---        2006-11-02     13:34      49680 twunk_16.exe
106:-a---        2006-11-02     13:34      31232 twunk_32.exe
109:-a---        2006-09-18     23:43     256192 winhelp.exe
110:-a---        2006-11-02     10:45       9216 winhlp32.exe

PS) grep /?

open read and close a file in 1 line of code

I think the most natural way for achieving this is to define a function.

def read(filename):
    f = open(filename, 'r')
    output =
    return output

Then you can do the following:

output = read('pagehead.section.htm')

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

How do I make a matrix from a list of vectors in R?

> library(plyr)
> as.matrix(ldply(a))
      V1 V2 V3 V4 V5 V6
 [1,]  1  1  2  3  4  5
 [2,]  2  1  2  3  4  5
 [3,]  3  1  2  3  4  5
 [4,]  4  1  2  3  4  5
 [5,]  5  1  2  3  4  5
 [6,]  6  1  2  3  4  5
 [7,]  7  1  2  3  4  5
 [8,]  8  1  2  3  4  5
 [9,]  9  1  2  3  4  5
[10,] 10  1  2  3  4  5

SVN: Is there a way to mark a file as "do not commit"?

Guys I just found a solution. Given that TortoiseSVN works the way we want, I tried to install it under Linux - which means, running on Wine. Surprisingly it works! All you have to do is:

  1. Add files you want to skip commit by running: "svn changelist 'ignore-on-commit' ".
  2. Use TortoiseSVN to commit: "~/.wine/drive_c/Program\ Files/TortoiseSVN/bin/TortoiseProc.exe /command:commit /path:'
  3. The files excluded will be unchecked for commit by default, while other modified files will be checked. This is exactly the same as under Windows. Enjoy!

(The reason why need to exclude files by CLI is because the menu entry for doing that was not found, not sure why. Any way, this works great!)

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Performance wise substring(0, 1) is better as found by following:

    String example = "something";
    String firstLetter  = "";

    long l=System.nanoTime();
    firstLetter = String.valueOf(example.charAt(0));
    System.out.println("String.valueOf: "+ (System.nanoTime()-l));

    firstLetter = Character.toString(example.charAt(0));
    System.out.println("Character.toString: "+ (System.nanoTime()-l));

    firstLetter = example.substring(0, 1);
    System.out.println("substring: "+ (System.nanoTime()-l));


String.valueOf: 38553
Character.toString: 30451
substring: 8660

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

The following worked for me:

  1. Go to the top right corner of IntelliJ -> click the icon
  2. In the Project Structure window -> Select project -> In the Project SDK, choose the correct version -> Click Apply -> Click Okay

Changing capitalization of filenames in Git

This Python snippet will git mv --force all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force.

Modify it to your liking. I just figured I'd share :)

import os
import re

searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']

for root, dirs, files in os.walk(searchDir):
    dirs[:] = [d for d in dirs if d not in exclude]
    for f in files:
        if re.match(r'[A-Z]', f):
            fullPath = os.path.join(root, f)
            fullPathLower = os.path.join(root, f[0].lower() + f[1:])
            command = 'git mv --force ' + fullPath + ' ' + fullPathLower

javascript node.js next()

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
  } else {

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

Capture iframe load complete event

<iframe> elements have a load event for that.

How you listen to that event is up to you, but generally the best way is to:

1) create your iframe programatically

It makes sure your load listener is always called by attaching it before the iframe starts loading.

var iframe = document.createElement('iframe');
iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src'
iframe.src = '...'; 
document.body.appendChild(iframe); // add it to wherever you need it in the document

2) inline javascript, is another way that you can use inside your HTML markup.

function onMyFrameLoad() {
  alert('myframe is loaded');

<iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe>

3) You may also attach the event listener after the element, inside a <script> tag, but keep in mind that in this case, there is a slight chance that the iframe is already loaded by the time you get to adding your listener. Therefore it's possible that it will not be called (e.g. if the iframe is very very fast, or coming from cache).

<iframe id="myframe" src="..."></iframe>

document.getElementById('myframe').onload = function() {
  alert('myframe is loaded');

Also see my other answer about which elements can also fire this type of load event

Find the 2nd largest element in an array with minimum number of comparisons

Use counting sort and then find the second largest element, starting from index 0 towards the end. There should be at least 1 comparison, at most n-1 (when there's only one element!).

How to use global variables in React Native?

Try to use = bar in or index.ios.js, then you can call in other file js.

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

How do I make a comment in a Dockerfile?

As others have mentioned, comments are referenced with a # and are documented here. However, unlike some languages, the # must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.

# This is a comment

COPY test_dir target_dir # This is not a comment, it is an argument to COPY

RUN echo hello world # This is an argument to RUN but the shell may ignore it

It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:

# escape=`

FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\

The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY and RUN commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax line. See the experimental syntax for more details on how this is being used in practice.

With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:

$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
 && echo third command

$ docker build .
Sending build context to Docker daemon  23.04kB
Step 1/2 : FROM busybox:latest
 ---> 59788edf1f3e
Step 2/2 : RUN echo first command  && echo third command
 ---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
 ---> 5442cfe321ac
Successfully built 5442cfe321ac

Upload Progress Bar in PHP

HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers

Segmentation Fault - C

char *s  does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;

This would not lead to segmentation fault error as you will not be refering to an unknown location anymore

Convert Decimal to Varchar

I think CAST(ROUND(yourColumn,2) as varchar) should do the job.

But why do you want to do this presentational formatting in T-SQL?

How to apply a patch generated with git format-patch?

If you want to apply it as a commit, use git am.

How can I change the image displayed in a UIImageView programmatically?

Working with Swift 5 (XCode 10.3) it's just

yourImageView.image = UIImage(named: "nameOfTheImage")

Difference between margin and padding?

One of the key differences between margin and padding is not mentioned in any of the answers: clickability and hover detection

Increasing the padding increases the effective size of the element. Sometimes I have a smallish icon that I don't want to make visibly larger but the user still needs to interact with that icon. I increase the icon's padding to give it a larger footprint for clicks and hover. Increasing the icon's margin will not have the same effect.

An answer to another question on this topic gives an example.

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

Jquery: Find Text and replace


isset PHP isset($_GET['something']) ? $_GET['something'] : ''

You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.


$something = isset($_GET['something']) ? $_GET['something'] : "failed";


if (isset($_GET['something'])) {
    $something = $_GET['something'];
} else {
    $something = "failed";

jQuery - multiple $(document).ready ...?

Both will get called, first come first served. Take a look here.

    $("#page-title").html("Document-ready was called!");

    $("#page-title").html("Document-ready 2 was called!");


Document-ready 2 was called!

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

Either fully avoid null in DB via NOT NULL and in Hibernate entity via @Column(nullable = false) accordingly or use Long wrapper instead of you long primitives.

A primitive is not an Object, therefore u can't assign null to it.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Hash function that produces short hashes?

Just summarizing an answer that was helpful to me (noting @erasmospunk's comment about using base-64 encoding). My goal was to have a short string that was mostly unique...

I'm no expert, so please correct this if it has any glaring errors (in Python again like the accepted answer):

import base64
import hashlib
import uuid

unique_id = uuid.uuid4()
# unique_id = UUID('8da617a7-0bd6-4cce-ae49-5d31f2a5a35f')

hash = hashlib.sha1(str(unique_id).encode("UTF-8"))
# hash.hexdigest() = '882efb0f24a03938e5898aa6b69df2038a2c3f0e'

result = base64.b64encode(hash.digest())
# result = b'iC77DySgOTjliYqmtp3yA4osPw4='

The result here is using more than just hex characters (what you'd get if you used hash.hexdigest()) so it's less likely to have a collision (that is, should be safer to truncate than a hex digest).

Note: Using UUID4 (random). See for the other types.

What data type to use in MySQL to store images?

Perfect answer for your question can be found on MYSQL site itself.refer their manual(without using PHP),17671,27914

According to them use LONGBLOB datatype. with that you can only store images less than 1MB only by default,although it can be changed by editing server config file.i would also recommend using MySQL workBench for ease of database management

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true

visit for more in info

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"


start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi


"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"


cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

Custom thread pool in Java 8 parallel stream

To measure the actual number of used threads, you can check Thread.activeCount():

    Runnable r = () -> IntStream
            .range(-42, +42)
            .map(i -> Thread.activeCount())

    new ForkJoinPool(42).submit(r).join();

This can produce on a 4-core CPU an output like:

5 // common pool
23 // custom pool

Without .parallel() it gives:

3 // common pool
4 // custom pool

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;

.min-100 {
    min-height: 100%;

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

Fixing slow initial load for IIS

A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

C# int to enum conversion

if (Enum.IsDefined(typeof(foo), value))
   return (Foo)Enum.Parse(typeof(foo), value);

Hope this helps

Edit This answer got down voted as value in my example is a string, where as the question asked for an int. My applogies; the following should be a bit clearer :-)

Type fooType = typeof(foo);

if (Enum.IsDefined(fooType , value.ToString()))
   return (Foo)Enum.Parse(fooType , value.ToString());

PHP array: count or sizeof?

sizeof() is just an alias of count() as mentioned here

How to check for registry value using VbScript

Try this. This script gets current logged in user's name & home directory:

On Error Resume Next

Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp) 

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp) 

How to make --no-ri --no-rdoc the default for gem install?

On Windows7 the .gemrc file is not present, you can let Ruby create one like this (it's not easy to do this in explorer).

gem sources --add

You will have to confirm (it's unsafe). Now the file is created in your userprofile folder (c:\users\)

You can edit the textfile to remove the source you added or you can remove it with

gem sources --remove

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

try ToString method for your desirer format use


OR you can use it with your variable of DateTime type


where dt is a DateTime variable

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/"
     href="" />


<link rel="icon" type="image/png"
     href="" />


<link rel="apple-touch-icon"

for the shortcut icon:

<link rel="shortcut icon"
     href="" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

How can I remove an element from a list?

In the case of named lists I find those helper functions useful

member <- function(list,names){
    ## return the elements of the list with the input names
    member..names <- names(list)
    index <- which(member..names %in% names)

exclude <- function(list,names){
     ## return the elements of the list not belonging to names
     member..names <- names(list)
     index <- which(!(member..names %in% names))
aa <- structure(list(a = 1:10, b = 4:5, fruits = c("apple", "orange"
)), .Names = c("a", "b", "fruits"))

> aa
## $a
##  [1]  1  2  3  4  5  6  7  8  9 10

## $b
## [1] 4 5

## $fruits
## [1] "apple"  "orange"

> member(aa,"fruits")
## $fruits
## [1] "apple"  "orange"

> exclude(aa,"fruits")
## $a
##  [1]  1  2  3  4  5  6  7  8  9 10

## $b
## [1] 4 5

Download file inside WebView

Try this out. After going through a lot of posts and forums, I found this.

mWebView.setDownloadListener(new DownloadListener() {       

    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded


Do not forget to give this permission! This is very important! Add this in your Manifest file(The AndroidManifest.xml file)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <!-- for your file, say a pdf to work -->

Hope this helps. Cheers :)

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;

Intersection and union of ArrayLists in Java

Unions and intersections defined only for sets, not lists. As you mentioned.

Check guava library for filters. Also guava provides real intersections and unions

 static <E> Sets.SetView<E >union(Set<? extends E> set1, Set<? extends E> set2)
 static <E> Sets.SetView<E> intersection(Set<E> set1, Set<?> set2)

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property


Use let...of instead of !!

If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in with of. As andreas has mentioned in the comments below for ... of iterates over values of an object while for ... in iterates over properties in an object. This is a new feature introduced in ES2015.

Simply replace:

<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">


<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">

So, you must replace in with of inside ngFor directive to get the values.

Detect backspace and del on "input" event?

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here

Saving numpy array to txt file row wise


' '.join(a)

and write this output to a file.

How to comment out a block of code in Python

In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.

Echo newline in Bash prints literal \n


echo -e "hello\nworld"

worked for me in nano editor.

From the man page:

-e enable interpretation of backslash escapes

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
    public myCallback: () => void;

    public doWork(): void
        //doing some work...
        this.myCallback(); //calling callback

VBScript How can I Format Date?

The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.

If you want your output to be "culture invariant", use myDateFormat() from's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use


Why aren't Xcode breakpoints functioning?

I've had problems with Xcode losing breakpoints when using the simulator and having the Scheme Launch setting to "wait for executable". Change that to "launch automatically" and breakpoints come back to life.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(
  2. Go to the Downloads section of the official Tesseract project ( EDIT: It's now located here:
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):


using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
    class Program
        public static void Main(string[] args)
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
                testImagePath = args[0];

                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                    using (var img = Pix.LoadFromFile(testImagePath))
                        using (logger.Begin("Process image"))
                            var i = 1;
                            using (var page = engine.Process(img))
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                        if (i % 2 == 0)
                                            using (logger.Begin("Line {0}", i))
                                                    using (logger.Begin("Word Iteration"))
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                            logger.Log("New block");
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                            logger.Log("New paragraph");
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                            logger.Log("New line");
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
            catch (Exception e)
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
            Console.Write("Press any key to continue . . . ");

        private class ResultPrinter
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
                this.logger = logger;

            public void Print(ResultIterator iter)
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));


using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
    public class FormattedConsoleLogger
        const string Tab = "    ";
        private class Scope : DisposableBase
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                this.indent = indent.ToString();

            public void Log(string format, object[] args)
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                        isNewLine = true;
                        i += 2;
                    else if (message[i] == '\r' || message[i] == '\n')
                        isNewLine = true;
                        if (isNewLine)
                            isNewLine = false;



            public Scope Begin()
                return new Scope(container, indentLevel + 1);

            protected override void Dispose(bool disposing)
                if (disposing)
                    var scope = container.scopes.Pop();
                    if (scope != this)
                        throw new InvalidOperationException("Format scope removed out of order.");

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
                scope = new Scope(this, 1);
                scope = ActiveScope.Begin();
            return scope;

        public void Log(string format, params object[] args)
            if (scopes.Count > 0)
                ActiveScope.Log(format, args);
                Console.WriteLine(String.Format(format, args));

        private Scope ActiveScope
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;

Access props inside quotes in React JSX

Note: In react you can put javascript expression inside curly bracket. We can use this property in this example.
Note: give one look to below example:

class LoginForm extends React.Component {

  constructor(props) {

    this.state = {i:1};

  handleClick() {
    this.setState(prevState => ({i : prevState.i + 1}));


  render() {

    return (
        <p onClick={this.handleClick.bind(this)}>Click to change image</p>
        <img src={'images/back'+ this.state.i+'.jpg'}/>


How To Set Up GUI On Amazon EC2 Ubuntu server

1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:

sudo apt-get update    sudo apt-get upgrade

5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.

sudo vim /etc/ssh/sshd_config

6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.

sudo /etc/init.d/ssh restart

8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.

sudo –i
passwd ubuntu

9) Switch back to the ubuntu user account and cd to the ubuntu home directory.

su ubuntu

10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop

11) Install xrdp

sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies

12) Make xfce4 the default window manager for RDP connections.

echo xfce4-session > ~/.xsession

13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.

sudo cp /home/ubuntu/.xsession /etc/skel

14) Open the xrdp.ini file to allow changing of the host port you will connect to.

sudo vim /etc/xrdp/xrdp.ini

(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)

15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).

- to -

16) Restart xrdp.

sudo service xrdp restart

17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.

18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.

19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.

See more details:

Maven error :Perhaps you are running on a JRE rather than a JDK?

This is how i fixed my problem

right clik on the project > properties > Java Compiler (select the one you are using)

it was 1.5 for me but i have 1.8 installed. so i changed it to 1.8.. and voilla it worked!.

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property: = ID;

reducing number of plot ticks

To solve the issue of customisation and appearance of the ticks, see the Tick Locators guide on the matplotlib website


Would set the total number of ticks in the x-axis to 3, and evenly distribute it across the axis.

There is also a nice tutorial about this

How to resize an Image C#

You could try net-vips, the C# binding for libvips. It's a lazy, streaming, demand-driven image processing library, so it can do operations like this without needing to load the whole image.

For example, it comes with a handy image thumbnailer:

Image image = Image.Thumbnail("image.jpg", 300, 300);

It also supports smart crop, a way of intelligently determining the most important part of the image and keeping it in focus while cropping the image. For example:

Image image = Image.Thumbnail("owl.jpg", 128, crop: "attention");

Where owl.jpg is an off-centre composition:


Gives this result:

Owl smart crop

First it shrinks the image to get the vertical axis to 128 pixels, then crops down to 128 pixels across using the attention strategy. This one searches the image for features which might catch a human eye, see Smartcrop() for details.

Select top 2 rows in Hive

select * from employee_list order by salary desc limit 2;

How to parse JSON boolean value?

Try this:

    "ACCOUNT_EXIST": true,
    "MultipleContacts": false

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}

What does the NS prefix mean?

The original code for the Cocoa frameworks came from the NeXTSTEP libraries Foundation and AppKit (those names are still used by Apple's Cocoa frameworks), and the NextStep engineers chose to prefix their symbols with NS.

Because Objective-C is an extension of C and thus doesn't have namespaces like in C++, symbols must be prefixed with a unique prefix so that they don't collide. This is particularly important for symbols defined in a framework.

If you are writing an application, such that your code is only likely ever to use your symbols, you don't have to worry about this. But if you're writing a framework or library for others' use, you should also prefix your symbols with a unique prefix. CocoaDev has a page where many developers in the Cocoa community have listed their "chosen" prefixes. You may also find this SO discussion helpful.

Generate random integers between 0 and 9

random.sample is another that can be used

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

I have been faced this problem.

The cause is your table don't have a primary key field.

And I have a simple solution: Set a field to primary key to specific filed that suit with your business logic. For example, I have database thesis_db and field thesis_id, I will press button Primary (key icon) to set thesis_id to become primary key field

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

What does '&' do in a C++ declaration?

In this context & is causing the function to take stringname by reference. The difference between references and pointers is:

  • When you take a reference to a variable, that reference is the variable you referenced. You don't need to dereference it or anything, working with the reference is sematically equal to working with the referenced variable itself.
  • NULL is not a valid value to a reference and will result in a compiler error. So generally, if you want to use an output parameter (or a pointer/reference in general) in a C++ function, and passing a null value to that parameter should be allowed, then use a pointer (or smart pointer, preferably). If passing a null value makes no sense for that function, use a reference.
  • You cannot 're-seat' a reference. While the value of a pointer can be changed to point at something else, a reference has no similar functionality. Once you take a variable by reference, you are effectively dealing with that variable directly. Just like you can't change the value of a by writing b = 4;. A reference's value is the value of whatever it referenced.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Only if anyone have the same situation like me, I am doing a tutorial of EntityFramework with existing database, but when the new database context is created on the models folders, we need to update the context in the startup, but not only in services.AddDbContext but AddIdentity too if you have users authentication

services.AddDbContext<NewDBContext>(options =>

services.AddIdentity<ApplicationUser, IdentityRole>()

what is Array.any? for javascript

I'm a little late to the party, but...

[].some(x => !!x)

How to center the content inside a linear layout?

android:gravity can be used on a Layout to align its children.

android:layout_gravity can be used on any view to align itself in its parent.

NOTE: If self or children is not centering as expected, check if width/height is match_parent and change to something else

Get difference between two lists

In case you want the difference recursively, I have written a package for python:


Install from PyPi:

pip install deepdiff

Example usage


>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

Same object returns empty

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))

Type of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

Value of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

Item added and/or removed

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

String difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

String difference 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'

>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
@@ -1,5 +1,4 @@

Type change

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

List difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

List difference 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

List difference ignoring order or duplicates: (with the same dictionaries as above)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)

List that contains dictionary:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}


>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

Named Tuples:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

Custom objects:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

Object attribute added:

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

How to run stored procedures in Entity Framework Core?

Currently EF 7 or EF Core does not support the old method of importing Stored procedures in designer and calling them directly. You can have a look at the roadmap to see what is going to be supported in the future: EF core roadmap.

So for now it is better to use SqlConnection to call stored procedures or any raw query, since you do not need the entire EF for this job. Here are two examples:

Call stored procedure that return single value. String in this case.

    @UserName nvarchar(50)
    SELECT 'Name is: '+@UserName;

Call stored procedure that return a list.

    SELECT [UserName], [Id] FROM [dbo].[AspNetUsers]

To call these stored procedure it is better to create static class that holds all of these functions, for example, I called it DataAccess class, as follows:

public static class DataAccess

        private static string connectionString = ""; //Your connection string
        public static string Test(String userName)
            using (SqlConnection conn = new SqlConnection(connectionString))

                // 1.  create a command object identifying the stored procedure
                SqlCommand cmd = new SqlCommand("dbo.Test", conn);

                // 2. set the command object so it knows to execute a stored procedure
                cmd.CommandType = CommandType.StoredProcedure;

                // 3. add parameter to command, which will be passed to the stored procedure
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));

                // execute the command
                using (var rdr = cmd.ExecuteReader())
                    if (rdr.Read())
                        return rdr[0].ToString();
                        return null;

        public static IList<Users> TestList()
            using (SqlConnection conn = new SqlConnection(connectionString))

                // 1.  create a command object identifying the stored procedure
                SqlCommand cmd = new SqlCommand("dbo.TestList", conn);

                // 2. set the command object so it knows to execute a stored procedure
                cmd.CommandType = CommandType.StoredProcedure;

                // execute the command
                using (var rdr = cmd.ExecuteReader())
                    IList<Users> result = new List<Users>();
                    //3. Loop through rows
                    while (rdr.Read())
                        //Get each column
                        result.Add(new Users() { UserName = (string)rdr.GetString(0), Id = rdr.GetString(1) });
                    return result;


And Users class is like this:

public class Users
     public string UserName { set; get; }
     public string Id { set; get; }

By the way you do not need to worry about the performance of opening and closing a connection for every request to sql as the is taking care of managing these for you. And I hope this was helpful.

Converting from IEnumerable to List

You can do this very simply using LINQ.

Make sure this using is at the top of your C# file:

using System.Linq;

Then use the ToList extension method.


IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();

Check number of arguments passed to a Bash script

There is a lot of good information here, but I wanted to add a simple snippet that I find useful.

How does it differ from some above?

  • Prints usage to stderr, which is more proper than printing to stdout
  • Return with exit code mentioned in this other answer
  • Does not make it into a one liner...
    _echoerr "Usage: $0 <args>"

    echo "$*" >&2

if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
    exit 2
main "$@"

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
    PrintWriter out = response.getWriter();

    out.println("<body bgcolor=\"white\">");

You can see this link for a simple hello world servlet

How can I count the occurrences of a list item?

Use Counter if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

Jquery bind double click and single click separately

This solution works for me

var DELAY = 250, clicks = 0, timer = null;

$(".fc-event").click(function(e) {
    if (timer == null) {
        timer = setTimeout(function() {
           clicks = 0;
            timer = null;
            // single click code
        }, DELAY);

    if(clicks === 1) {
         timer = null;
         clicks = -1;
         // double click code

How to connect to remote Redis server?

In Case of password also we need to pass one more parameter

redis-cli -h host -p port -a password

How do I protect Python code?

I understand that you want your customers to use the power of python but do not want expose the source code.

Here are my suggestions:

(a) Write the critical pieces of the code as C or C++ libraries and then use SIP or swig to expose the C/C++ APIs to Python namespace.

(b) Use cython instead of Python

(c) In both (a) and (b), it should be possible to distribute the libraries as licensed binary with a Python interface.

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

Efficiently finding the last line in a text file

lines = file.readlines()
last_line = lines[-1]

How to properly set the 100% DIV height to match document/window height?

I figured it out myself with the help of someone's answer. But he deleted it for some reason.

Here's the solution:

  1. remove all CSS height hacks and 100% heights
  2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
  3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
  4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

        var windowH = $(window).height();
        var wrapperH = $('#wrapper').height();
        if(windowH > wrapperH) {                            
            var windowH = $(window).height();
            var wrapperH = $('#wrapper').height();
            var differenceH = windowH - wrapperH;
            var newH = wrapperH + differenceH;
            var truecontentH = $('#truecontent').height();
            if(windowH > truecontentH) {
                $('#wrapper').css('height', (newH)+'px');

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete /*# */ in css/bootstrap.min.css

and delete /*# */ in css/bootstrap.css

How to read from a file or STDIN in Bash?

Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen - this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV. None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec appropriately.


(($#)) || set -- -
while (($#)); do
   { [[ $1 = - ]] || exec < "$1"; } &&
   while read -r; do
      printf '%s\n' "$REPLY"

Filename's available in $1.

If no arguments are given, we artificially set - as the first positional parameter. We then loop on the parameters. If a parameter is not -, we redirect standard input from filename with exec. If this redirection succeeds we loop with a while loop. I'm using the standard REPLY variable, and in this case you don't need to reset IFS. If you want another name, you must reset IFS like so (unless, of course, you don't want that and know what you're doing):

while IFS= read -r line; do
    printf '%s\n' "$line"

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Python equivalent of a given wget command

Let me Improve a example with threads in case you want download many files.

import math
import random
import threading

import requests
from clint.textui import progress

# You must define a proxy list
# I suggests
proxies = {
    0: {'http': ''},
    1: {'http': ''},
    2: {'http': ''},
    3: {'http': ''}

# you must define the list for files do you want download
videos = [

downloaderses = list()

def downloaders(video, selected_proxy):
    print("Downloading file named {} by proxy {}...".format(video, selected_proxy))
    r = requests.get(video, stream=True, proxies=selected_proxy)
    nombre_video = video.split("/")[3]
    with open(nombre_video, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in, expected_size=(total_length / 1024) + 1):
            if chunk:

for video in videos:
    selected_proxy = proxies[math.floor(random.random() * len(proxies))]
    t = threading.Thread(target=downloaders, args=(video, selected_proxy))

for _downloaders in downloaderses:

Jquery Button Click Event via ajax

I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

To cater for that possibility, I would do the following:

$(document).ready(function() {
  $('#<%=myButton.ClientID %>').click(function() {
    // Do client side button click stuff here.

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.

Changing background color of selected item in recyclerview

My solution:

public static class SimpleItemRecyclerViewAdapter
        extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {

    private final MainActivity mParentActivity;
    private final List<DummyContent.DummyItem> mValues;
    private final boolean mTwoPane;
    private static int lastClickedPosition=-1;
    **private static View viewOld=null;**
    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View view) {
            DummyContent.DummyItem item = (DummyContent.DummyItem) view.getTag();
            if (mTwoPane) {
                Bundle arguments = new Bundle();
                ItemDetailFragment fragment = new ItemDetailFragment();
                        .replace(, fragment)
            } else {
                Context context = view.getContext();
                Intent intent = new Intent(context, ItemDetailActivity.class);



viewOld is null at the beginning, then points to the last selected view. With onClick you change the background of the selected view and redefine the background of the penultimate view selected. Simple and functional.

Representing null in JSON

According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}), or a list with a null value ([null]), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}) or an empty list ([]) are perfectly fine, but aren't null either.

In Python:

>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
>>> print json.loads('[]')
>>> print json.loads('{}')
>>> print json.loads('null')

How to git-cherry-pick only changes to certain files?

Perhaps the advantage of this method over Jefromi's answer is that you don't have to remember which behaviour of git reset is the right one :)

 # Create a branch to throw away, on which we'll do the cherry-pick:
 git checkout -b to-discard

 # Do the cherry-pick:
 git cherry-pick stuff

 # Switch back to the branch you were previously on:
 git checkout -

 # Update the working tree and the index with the versions of A and B
 # from the to-discard branch:
 git checkout to-discard -- A B

 # Commit those changes:
 git commit -m "Cherry-picked changes to A and B from [stuff]"

 # Delete the temporary branch:
 git branch -D to-discard

Using the star sign in grep

The "star sign" is only meaningful if there is something in front of it. If there isn't the tool (grep in this case) may just treat it as an error. For example:

'*xyz'    is meaningless
'a*xyz'   means zero or more occurrences of 'a' followed by xyz

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Python - List of unique dictionaries

I have summarized my favorites to try out:

# ----------------------------------------------
# Setup
# ----------------------------------------------

myList = [
  {"id":"1", "lala": "value_1"},
  {"id": "2", "lala": "value_2"}, 
  {"id": "2", "lala": "value_2"}, 
  {"id": "3", "lala": "value_3"}
print("myList:", myList)

# -----------------------------------------------
# Option 1 if objects has an unique identifier
# -----------------------------------------------

myUniqueList = list({myObject['id']:myObject for myObject in myList}.values())
print("myUniqueList:", myUniqueList)

# -----------------------------------------------
# Option 2 if uniquely identified by whole object
# -----------------------------------------------

myUniqueSet = [dict(s) for s in set(frozenset(myObject.items()) for myObject in myList)]
print("myUniqueSet:", myUniqueSet)

# -----------------------------------------------
# Option 3 for hashable objects (not dicts)
# -----------------------------------------------

myHashableObjects = list(set(["1", "2", "2", "3"]))
print("myHashAbleList:", myHashableObjects)

How do you overcome the svn 'out of date' error?

I just got this error. What I recommend is you first check on your server if the original file is there. Sometimes the changes aren't made in your local folder. If this is your situation, just delete your folder and checkout again.

Android : difference between invisible and gone?


This view is invisible, but it still takes up space for layout purposes.


This view is invisible, and it doesn't take any space for layout purposes.

Git push/clone to new server

What you may want to do is first, on your local machine, make a bare clone of the repository

git clone --bare /path/to/repo /path/to/bare/repo.git  # don't forget the .git!

Now, archive up the new repo.git directory using tar/gzip or whatever your favorite archiving tool is and then copy the archive to the server.

Unarchive the repo on your server. You'll then need to set up a remote on your local repository:

git remote add repo-name user@host:/path/to/repo.git #this assumes you're using SSH

You will then be able to push to and pull from the remote repo with:

git push repo-name branch-name
git pull repo-name branch-name

How do I simulate a low bandwidth, high latency environment?

To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.

MISCONF Redis is configured to save RDB snapshots

In my case it was related to disk free space. (you can check it with df -h bash command) when I free some space this error disappeared.

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:


ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Retrieve a Fragment from a ViewPager

You don't need to call getItem() or some other method at later stage to get the reference of a Fragment hosted inside ViewPager. If you want to update some data inside Fragment then use this approach: Update ViewPager dynamically?

Key is to set new data inside Adaper and call notifyDataSetChanged() which in turn will call getItemPosition(), passing you a reference of your Fragment and giving you a chance to update it. All other ways require you to keep reference to yourself or some other hack which is not a good solution.

public int getItemPosition(Object object) {
    if (object instanceof UpdateableFragment) {
        ((UpdateableFragment) object).update(xyzData);
    //don't return POSITION_NONE, avoid fragment recreation. 
    return super.getItemPosition(object);

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I had the same error because I switched from XML- to java-configuration.

The point was, I didn't migrate <tx:annotation-driven/> tag, as Stone Feng suggested.

So I just added @EnableTransactionManagement as suggested here Setting Up Annotation Driven Transactions in Spring in @Configuration Class, and it works now

Can I pass parameters in computed properties in Vue.Js

computed: {
  fullName: (app)=> (salut)=> {
      return salut + ' ' + this.firstName + ' ' + this.lastName    

when you want use

<p>{{fullName('your salut')}}</p>

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
  • Scala

    val exprs = -> "mean")).toMap
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    exprs = [min(x) for x in df.columns]
  • Scala

    import org.apache.spark.sql.functions.sum
    val exprs =
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

Command failed due to signal: Segmentation fault: 11

In my case, IGListKit refactored their class named IGListSectionController to ListSectionController , while I already had a class named ListSectionController. I used find and replace and didn't know I had a class with the same name.

class ListSectionController : ListSectionController

I read the error message in full and concluded that this error can also happen when you have Circular dependencies. This wasn't mentioned in any of the comments, I hope this helps.

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

wget can't download - 404 error

I had the same problem. Solved using single quotes like this:

$ wget ''

wget version in use:

$ wget --version
GNU Wget 1.11.4 Red Hat modified

Java math function to convert positive int to negative and negative to positive?

You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE! If you do 0 - MIN_VALUE the answer is still MIN_VALUE.

Testing two JSON objects for equality ignoring child order in Java

I would do the following,

JSONObject obj1 = /*json*/;
JSONObject obj2 = /*json*/;

ObjectMapper mapper = new ObjectMapper();

JsonNode tree1 = mapper.readTree(obj1.toString());
JsonNode tree2 = mapper.readTree(obj2.toString());

return tree1.equals(tree2);

Removing duplicate characters from a string

Create a list in Python and also a set which doesn't allow any duplicates. Solution1 :

def fix(string):
    s = set()
    list = []
    for ch in string:
        if ch not in s:

    return ''.join(list)        

string = "Protiijaayiiii"

Method 2 :

s = "Protijayi"

aa = [ ch  for i, ch in enumerate(s) if ch not in s[:i]]

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*, axis=1)
>>> df
   b  c  index_x10
1  2  3         10
4  5  6         40

Reset the Value of a Select Box

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

    <option selected>three</option>
  <input type="reset" value="Reset" />

Or, using JavaScript, it can be done in following way:

HTML Code:

  <option selected>one</option>
<button id="revert">Reset</button>

And JavaScript code:

const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;

Both of these methods will work if you have multiple selected items or single selected item.

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Google Maps API v3 marker with label

In order to add a label to the map you need to create a custom overlay. The sample at uses a custom class, Layer, that inherits from OverlayView (which inherits from MVCObject) from the Google Maps API. He has a revised version (adds support for visibility, zIndex and a click event) which can be found here:

The following code is taken directly from Marc Ridey's Blog (the revised link above).

Layer class

// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
  // Initialization

  // Label specific
  var span = this.span_ = document.createElement('span'); = 'position: relative; left: -50%; top: -8px; ' +
  'white-space: nowrap; border: 1px solid blue; ' +
  'padding: 2px; background-color: white';

  var div = this.div_ = document.createElement('div');
  div.appendChild(span); = 'position: absolute; display: none';
Label.prototype = new google.maps.OverlayView;

// Implement onAdd
Label.prototype.onAdd = function() {
  var pane = this.getPanes().overlayImage;

  // Ensures the label is redrawn if the text or position is changed.
  var me = this;
  this.listeners_ = [
    google.maps.event.addListener(this, 'position_changed', function() { me.draw(); }),
    google.maps.event.addListener(this, 'visible_changed', function() { me.draw(); }),
    google.maps.event.addListener(this, 'clickable_changed', function() { me.draw(); }),
    google.maps.event.addListener(this, 'text_changed', function() { me.draw(); }),
    google.maps.event.addListener(this, 'zindex_changed', function() { me.draw(); }),
    google.maps.event.addDomListener(this.div_, 'click', function() {
      if (me.get('clickable')) {
        google.maps.event.trigger(me, 'click');

// Implement onRemove
Label.prototype.onRemove = function() {

 // Label is removed from the map, stop updating its position/text.
 for (var i = 0, I = this.listeners_.length; i < I; ++i) {

// Implement draw
Label.prototype.draw = function() {
 var projection = this.getProjection();
 var position = projection.fromLatLngToDivPixel(this.get('position'));

 var div = this.div_; = position.x + 'px'; = position.y + 'px'; = 'block';

 this.span_.innerHTML = this.get('text').toString();


    <meta http-equiv="content-type" content="text/html; charset=utf-8">
      Label Overlay Example
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="label.js"></script>
    <script type="text/javascript">
      var marker;

      function initialize() {
        var latLng = new google.maps.LatLng(40, -100);

        var map = new google.maps.Map(document.getElementById('map_canvas'), {
          zoom: 5,
          center: latLng,
          mapTypeId: google.maps.MapTypeId.ROADMAP

        marker = new google.maps.Marker({
          position: latLng,
          draggable: true,
          zIndex: 1,
          map: map,
          optimized: false

        var label = new Label({
          map: map
        label.bindTo('position', marker);
        label.bindTo('text', marker, 'position');
        label.bindTo('visible', marker);
        label.bindTo('clickable', marker);
        label.bindTo('zIndex', marker);

        google.maps.event.addListener(marker, 'click', function() { alert('Marker has been clicked'); })
        google.maps.event.addListener(label, 'click', function() { alert('Label has been clicked'); })

      function showHideMarker() {

      function pinUnpinMarker() {
        var draggable = marker.getDraggable();
  <body onload="initialize()">
    <div id="map_canvas" style="height: 200px; width: 200px"></div>
    <button type="button" onclick="showHideMarker();">Show/Hide Marker</button>
    <button type="button" onclick="pinUnpinMarker();">Pin/Unpin Marker</button>

Build an iOS app without owning a mac?

Update Intel XDK is no longer available.

You can use Intel XDK with that you can develop and publish an app for iOS without the mac.

Click here for detail.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

In Bootstrap 3,How to change the distance between rows in vertical?


Bootstrap 4 has spacing utilities to handle this

.mt-0 {
  margin-top: 0 !important;



If you are using SASS, this is what I normally do.

$margins: (xs: 0.5rem, sm: 1rem, md: 1.5rem, lg: 2rem, xl: 2.5rem);

@each $name, $value in $margins {
  .margin-top-#{$name} {
    margin-top: $value;

  .margin-bottom-#{$name} {
    margin-bottom: $value;

so you can later use margin-top-xs for example

How to list all functions in a Python module?

Once you've imported the module, you can just do:


... To get the docs on all the functions at once, interactively. Or you can use:


... To simply list the names of all the functions and variables defined in the module.

IIS Manager in Windows 10

@user1664035 & @Attila Mika's suggestion worked. You have to navigate to Control Panel -> Programs And Features -> Turn Windows Features On or Off. And refer to the screenshot. You should check IIS Management console.


Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

I've noticed that sometimes eclipse somehow picks up some of the jars and keeps a lock on them (in Windows only) and when you try to do mvn clean it says:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.2:clean (default-clean) on project

The only solution so far is to close eclipse and run the mvn build again.

And these are random jars - it can pick up anything it wants... Why that happens is a mystery to me. Probably eclipse opens the jars when you do Type Search or Resource Search and forgets to close them / release the file handlers..

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

Giving a border to an HTML table row, <tr>

adding border-spacing: 0rem 0.5rem; creates a space for each cell (td, th) items on its bottom while leaving no space between the cells{
        border-collapse: separate;
        border-spacing: 0rem 0.5rem;
    } thead tr.border-row the, tbody tr.border-row td, tbody tr.border-row th{
        border-top: 1px solid #EAEAEA;
        border-bottom: 1px solid #EAEAEA;
        vertical-align: middle;
        white-space: nowrap;
        font-size: 0.875rem;
    } thead tr.border-row th:first-child, tbody tr.border-row td:first-child{
        border-left: 1px solid #EAEAEA;
    } thead tr.border-row th:last-child, tbody tr.border-row td:last-child{
        border-right: 1px solid #EAEAEA;

Spring MVC Multipart Request with JSON

As documentation says:

Raised when the part of a "multipart/form-data" request identified by its name cannot be found.

This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.