Programs & Examples On #Displaylist

Android Canvas: drawing too large bitmap

if you use Picasso change to Glide like this.

Remove picasso

Picasso.get().load(Uri.parse("url")).into(imageView)

Change Glide

Glide.with(context).load("url").into(imageView)

More efficient Glide than Picasso draw to large bitmap

Multiple glibc libraries on a single host

Can you consider using Nix http://nixos.org/nix/ ?

Nix supports multi-user package management: multiple users can share a common Nix store securely, don’t need to have root privileges to install software, and can install and use different versions of a package.

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

How can I get Git to follow symlinks?

I got tired of every solution in here either being outdated or requiring root, so I made an LD_PRELOAD-based solution (Linux only).

It hooks into Git's internals, overriding the 'is this a symlink?' function, allowing symlinks to be treated as their contents. By default, all links to outside the repo are inlined; see the link for details.

How do I suspend painting for a control and its children?

At my previous job we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.

After a lot of googling and reflector usage I came across the WM_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.

This is a very very simple class demonstrating how to use this message:

class DrawingControl
{
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

    private const int WM_SETREDRAW = 11; 

    public static void SuspendDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
    }

    public static void ResumeDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
        parent.Refresh();
    }
}

There are fuller discussions on this - google for C# and WM_SETREDRAW, e.g.

C# Jitter

Suspending Layouts

And to whom it may concern, this is similar example in VB:

Public Module Extensions
    <DllImport("user32.dll")>
    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
    End Function

    Private Const WM_SETREDRAW As Integer = 11

    ' Extension methods for Control
    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
        SendMessage(Target.Handle, WM_SETREDRAW, True, 0)
        If Redraw Then
            Target.Refresh()
        End If
    End Sub

    <Extension()>
    Public Sub SuspendDrawing(ByVal Target As Control)
        SendMessage(Target.Handle, WM_SETREDRAW, False, 0)
    End Sub

    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control)
        ResumeDrawing(Target, True)
    End Sub
End Module

Get the last item in an array

For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );

Skip first entry in for loop in python?

Well, your syntax isn't really Python to begin with.

Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container. In this case, the container is the cars list, but you want to skip the first and last elements, so that means cars[1:-1] (python lists are zero-based, negative numbers count from the end, and : is slicing syntax.

So you want

for c in cars[1:-1]:
    do something with c

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

how to have two headings on the same line in html

The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.

The HTML Part:

<h1 class="text-left-right">
    <span class="left-text">Heading Goes Here</span>
    <span class="byline">Byline here</span>
</h1>

And the CSS:

.text-left-right {
    text-align: right;
    position: relative;
}
.left-text {
    left: 0;
    position: absolute;
}
.byline {
    font-size: 16px;
    color: rgba(140, 140, 140, 1);
}

Node.js setting up environment specific configs to be used with everyauth

A very useful solution is use the config module.

after install the module:

$ npm install config

You could create a default.json configuration file. (you could use JSON or JS object using extension .json5 )

For example

$ vi config/default.json

{
  "name": "My App Name",
  "configPath": "/my/default/path",
  "port": 3000
}

This default configuration could be override by environment config file or a local config file for a local develop environment:

production.json could be:

{
  "configPath": "/my/production/path",
  "port": 8080
}

development.json could be:

{
  "configPath": "/my/development/path",
  "port": 8081
}

In your local PC you could have a local.json that override all environment, or you could have a specific local configuration as local-production.json or local-development.json.

The full list of load order.

Inside your App

In your app you only need to require config and the needed attribute.

var conf = require('config'); // it loads the right file
var login = require('./lib/everyauthLogin', {configPath: conf.get('configPath'));

Load the App

load the app using:

NODE_ENV=production node app.js

or setting the correct environment with forever or pm2

Forever:

NODE_ENV=production forever [flags] start app.js [app_flags]

PM2 (via shell):

export NODE_ENV=staging
pm2 start app.js

PM2 (via .json):

process.json

{
   "apps" : [{
    "name": "My App",
    "script": "worker.js",
    "env": {
      "NODE_ENV": "development",
    },
    "env_production" : {
       "NODE_ENV": "production"
    }
  }]
}

And then

$ pm2 start process.json --env production

This solution is very clean and it makes easy set different config files for Production/Staging/Development environment and for local setting too.

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

Two's Complement in Python

Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:

def s12(value):
    return -(value & 0b100000000000) | (value & 0b011111111111)

The first bitwise-and operation is used to sign-extend negative numbers (most significant bit is set), while the second is used to grab the remaining 11 bits. This works since integers in Python are treated as arbitrary precision two's complement values.

You can then combine this with the int function to convert a string of binary digits into the unsigned integer form, then interpret it as a 12-bit signed value.

>>> s12(int('111111111111', 2))
-1
>>> s12(int('011111111111', 2))
2047
>>> s12(int('100000000000', 2))
-2048

One nice property of this function is that it's idempotent, thus the value of an already signed value will not change.

>>> s12(-1)
-1

Select all DIV text with single mouse click

_x000D_
_x000D_
function selectText(containerid) {_x000D_
    if (document.selection) { // IE_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select();_x000D_
    } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().removeAllRanges();_x000D_
        window.getSelection().addRange(range);_x000D_
    }_x000D_
}
_x000D_
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
_x000D_
_x000D_
_x000D_

Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.

Removing time from a Date object?

You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static Date removeTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

}

How to add/subtract dates with JavaScript?

You need to use getTime() and setTime() to add or substract the time in a javascript Date object. Using setDate() and getDate() will lead to errors when reaching the limits of the months 1, 30, 31, etc..

Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:

var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

I'm using ASP.NET SPA Extensions which creates me a proxy on ports 5000 and 5001 that pass through to Angular's port 4200 during development.

I had had CORS correctly setup for https port 5001 and everything was fine, but I inadvertently went to an old bookmark which was for port 5000. Then suddenly this message arose. As others have said in the console there was a 'preflight' error message.

So regardless of your environment, if you're using CORS make sure you have all ports specified - as the host and port both matter.

Use of #pragma in C

Putting #pragma once at the top of your header file will ensure that it is only included once. Note that #pragma once is not standard C99, but supported by most modern compilers.

An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */)

"Debug only" code that should run only when "turned on"

What you're looking for is

[ConditionalAttribute("DEBUG")]

attribute.

If you for instance write a method like :

[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
    Console.WriteLine("This message was brought to you by your debugger : ");
    Console.WriteLine(message);
}

any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.

Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

I have a solution for Java/JPA/eclipselink/oracle when insert a long xml string (>4000) into a XMLTYPE column at Insert XML with more than 4000 characters into a Oracle XMLTYPE column. For clarity, include the same contents here in case the link not working

You need to convert xml string for more than 4000 charcaters into SQLXML type first.

Environment: jpa 2.1.0, eclipselink 2.5.2, oracle db 11gr2

SQL:

CREATE TABLE "XMLTEST"
( "ID" NUMBER(10,0) NOT NULL ENABLE, 
  "DESCRIPTION" VARCHAR2(50 CHAR) NOT NULL ENABLE, 
  "XML_TXT" "XMLTYPE" NOT NULL ENABLE
);

INSERT INTO XMLTEST (ID, DESCRIPTION, XML_TXT) VALUES (101, 'XML DATA', '<data>TEST</data>');
COMMIT;

DROP TABLE "XMLTEST";

Java Code

String sql = "INSERT INTO XMLTEST (ID, DESCRIPTION, XML_TXT) VALUES (?, ?, ?)";
String xmlDataStr = "<data>test...</data>"; // a long xml string with length > 4000 characters
Connection con = getEntityManager().unwrap(Connection.class);
SQLXML sqlXml = con.createSQLXML();
sqlXml.setString(xmlDataStr);

Java code - use PreparedStatement

PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setLong(1, 201);
pstmt.setLong(2, "Long XML Data");
pstmt.setSQLXML(3, sqlXml);
pstmt.execute();

Java code - use native query instead of PreparedStatement

Query query = getEntityManager().createNativeQuery(sql);
query.setParameter(1, 301);
query.setParameter(2, "Long XML Data");
query.setParameter(3, sqlXml);
query.executeUpdate();

PowerShell to remove text from a string

I referenced @benjamin-hubbard 's answer above to parse the output of dnscmd for A records, and generate a PHP "dictionary"/key-value pairs of IPs and Hostnames. I strung multiple -replace args together to replace text with nothing or tab to format the data for the PHP file.

$DnsDataClean = $DnsData `
    -match "^[a-zA-Z0-9].+\sA\s.+" `
    -replace "172\.30\.","`$P." `
    -replace "\[.*\] " `
    -replace "\s[0-9]+\sA\s","`t"

$DnsDataTable = ( $DnsDataClean | `
    ForEach-Object { 
        $HostName = ($_ -split "\t")[0] ; 
        $IpAddress = ($_ -split "\t")[1] ; 
        "`t`"$IpAddress`"`t=>`t'$HostName', `n" ;
    } | sort ) + "`t`"`$P.255.255`"`t=>`t'None'"

"<?php
`$P = '10.213';
`$IpHostArr = [`n`n$DnsDataTable`n];

?>" | Out-File -Encoding ASCII -FilePath IpHostLookups.php

Get-Content IpHostLookups.php

Delete all items from a c++ std::vector

vector.clear() should work for you. In case you want to shrink the capacity of the vector along with clear then

std::vector<T>(v).swap(v);

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

How do I correctly clone a JavaScript object?

If you're okay with a shallow copy, the underscore.js library has a clone method.

y = _.clone(x);

or you can extend it like

copiedObject = _.extend({},originalObject);

HTTP POST Returns Error: 417 "Expectation Failed."

The web.config approach works for InfoPath form services calls to IntApp web service enabled rules.

  <system.net>
    <defaultProxy />
    <settings> <!-- 20130323 bchauvin -->
        <servicePointManager expect100Continue="false" />
    </settings>
  </system.net>

Insert some string into given string at given index in Python

Implementation

The functions below will allow one to insert one string into another string:

def str_insert(from_me, into_me, at):
    """
    Inserts the string <from_me> into <into_me>

    Input <at> must be an integer index of <into_me> or a substring of <into_me>

    Inserts <from_me> AFTER <at>, not before <at>

    Inputs <from_me> and <into_me> must have working __str__ methods defined.
    This is satisfied if they already are strings.

    If not already strings, <from_me>, <into_me> are converted into strings.

    If you try to insert an empty string, that's fine, and the result
    is no different from the original.

    In order to insert 'from_me' after nothing (insert at the beginning of the string) use:
        at = ''  or  at = 0
    """
    try:
        return str_insert_or_raise(from_me, into_me, at)
    except ValueError as err:
        serr = str(err)
        if (str_insert_or_raise.__name__ in serr) and 'not found' in serr and '<at>' in serr:
            # if can't find where to insert stuff, don't bother to insert it
            # use str_insert_or_raise if you want an exception instead
            return into_me
        else:
            raise err

##############################################################

def str_insert_or_raise(from_me, into_me, at):
    """
    Inserts the string <from_me> into <into_me>

    Inserts <from_me> AFTER <at>, not before <at>

    Input <at> must be an integer index of <into_me> or a substring of <into_me>

    If <at> is the string '15', that substring will be searched for,
    '15' will not be interpreted as an index/subscript.        

    Inputs <from_me> and <into_me> must have working __str__ methods defined.
    If not already strings, <from_me>, <into_me> are converted into strings. 

    If you try to insert something, but we cannot find the position where
    you said to insert it, then an exception is thrown guaranteed to at least
    contain the following three substrings:
        str_insert_or_raise.__name__
        'not found'
        '<at>'
    """
    try:
        if isinstance(at, int):
            return str_insert_by_int(from_me, into_me, at)
        # Below, the calls to str() work fine if <at> and <from_me> are already strings
        # it makes them strings if they are not already
        return str_insert_by_str(str(from_me), str(into_me), str(at))
    except ValueError as err:
        serr = str(err)
        if 'empty string' in serr:
            return into_me # We allow insertion of the empty string
        elif ("<at>" in serr) and 'not found' in serr:
            msg_start = "In " + str_insert_or_raise.__name__ + ":  "
            msg = [msg_start, "\ninput ", "<at> string", " not found in ", "<into_me>",
                              "\ninput <",   str(at)  , "> not found in <", str(into_me), ">"]
            msg = ''.join(msg)
            raise ValueError(msg) from None
        else:
           raise err
#############################################################
def str_insert_by_str(from_me, into_me, at):
    """
    Inserts the string <from_me> into <into_me>

    puts 'from_me' AFTER 'at', not before 'at'
    For example,
        str_insert_or_raise(at = '2',  from_me = '0', into_me = '123')
    puts the zero after the 2, not before the 2
    The call returns '1203' not '1023'

    Throws exceptions if input arguments are not strings.

    Also, if <from_me> is empty or <at> is not a substring of <into_me> then
    an exception is raised.

    For fewer exceptions, use <str_insert_or_raise> instead.
    """
    try:
        s = into_me.replace(at, at + from_me, 1)
    except TypeError as terr: # inputs to replace are not strings
        msg_list = ['Inputs to function ', str_insert_by_str.__name__, '() must be strings']
        raise TypeError(''.join(msg_list)) from None
    # At the end of call to replace(), the '1'  indicates we will replace
    # the leftmost occurrence of <at>, instead of every occurrence of <at>
    if (s == into_me): # <at> string not found and/or <from_me> is the empty string
        msg_start = "In " + str_insert_by_str.__name__ + ":  "
        if from_me == '':
            msg = ''.join([msg_start, "attempted to insert an empty string"])
            raise ValueError(msg) from None
        raise ValueError(msg_start, "Input <at> string not found in <into_me>.",
                                    "\nUnable to determine where you want the substring inserted.") from None
    return s
##################################################
def str_insert_by_int(from_me, into_me, at):
    """
    * Inserts the string <from_me> into <into_me> at integer index <at>    
    * throws exceptions if input arguments are not strings.    
    * Also, throws an  exception if you try to insert the empty string    
    * If <at> is less than zero, <from_me> gets placed at the
      beginning of <into_me>    
    * If <at> is greater than the largest index of <into_me>,
      <from_me> gets placed after the end of <into_me>

    For fewer exceptions, use <str_insert_or_raise> instead.
    """
    at = into_me[:(at if at > 0 else 0)]
    return str_insert_by_str(from_me, into_me, at)

Usage

The code below demonstrates how to call the str_insert function given earlier

def foo(*args):
    return args

F = 'F. '

s = 'Using the string \'John \' to specify where to make the insertion'
result = str_insert(from_me = F, into_me ='John Kennedy', at ='John ')
print(foo('\n\n', s, '\n', result))

s = 'Using an int returned by find(\'Ken\') to specify where to make the insertion'
index = 'John Kennedy'.find('Ken') # returns the position of the first letter of 'Ken', not the last letter
result = str_insert(from_me = F, into_me ='John Kennedy', at = index)
print(foo('\n\n', s, '\n', result))

s = 'Using an int (5) to specify where to make the insertion.'
result = str_insert(from_me = F, into_me ='John Kennedy', at = 5)
print(foo('\n\n', s, '\n', result))

s = "Looking for an 'at' string which does not exist"
result = str_insert(from_me = F, into_me ='John Kennedy', at ='x')
print(foo('\n\n', s, '\n', result))

s = ''.join(["Looking for the empty string.",
             "\nFind one immediately at the beginning of the string"])
result = str_insert(from_me = F, into_me ='John Kennedy', at = '')
print(foo('\n\n', s, '\n', result))

s = "Insert an empty string at index 3. No visible change"
result = str_insert(from_me = '', into_me = 'John Kennedy', at = 3)
print(foo('\n\n', s, '\n', result))    

for index in [-5, -1, 0, 1, 997, 999]:
    s = "index " + str(index)
    result = str_insert(from_me = F, into_me = 'John Kennedy', at = index)
    print(foo('\n\n', s, '\n', result))

Warning About Lack of Ability to Modify In-Place

None of the functions above will modify a string "in-place." The functions each return a modified copy of the string, but the original string remains intact.

For example,

s = ''.join(["Below is what we get when we forget ",
             "to overwrite the string with the value",
             " returned by str_insert_or_raise:"])

examp_str = 'John Kennedy'
str_insert('John ', F, examp_str)
print(foo('\n\n', s, '\n', examp_str))

# examp_str is still 'John Kennedy' without the F

"Could not find bundler" error

Can be related to https://github.com/bundler/bundler-features/issues/34 if you are running the command inside another bundle exec. Try using Bundler.with_original_env if that is the case.

Show values from a MySQL database table inside a HTML table on a webpage

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
     border: 1px solid black;
}
</style>
</head>
<center>
<body>

<?php

$con = mysql_connect("localhost","root","");
mysql_select_db("rachna",$con);



$query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'A' GROUP BY Iyear";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
     echo "<table><tr><th></th><th>1999</th><th>2000</th><th>2001</th><th>2003</th></tr>";
     echo "<th>A</th>"; 

     //Code for A Customer-------------------------------------------
     while($row =mysql_fetch_array($result)) {
         echo "<th>" . $row['RESULT'] . "</th>";
         }

          echo"<tr></tr>";  

           //COde of B Customer--------------------------------------

         echo "<th>B</th>";
     $query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'B' GROUP BY Iyear";
    $result1 = mysql_query($query) or die(mysql_error());


     while($row = mysql_fetch_array($result1)) {
         echo "<th> " . $row["RESULT"]. "</th>";
     }
     echo "</table>";
} else {
     echo "0 results";
}


?>  
</center>
</body>
</html>

Google Maps: How to create a custom InfoWindow?

EDIT After some hunting around, this seems to be the best option:

https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html

You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:


There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.

Certificate is trusted by PC but not by Android

I encountered this same issue under Apache 2.2 when I was trying to use multiple SSLCertificateChainFile directives for each intermediate cert; instead I needed to concatenate all three into a single file. Coming from GoDaddy where they'd done this for me as a "bundle" this extra step was new to me, but a re-reading of the Apache documentation made this apparent.

Worth noting, this directive is deprecated as of Apache 2.4.8 since you can now concatenate all the intermediates with the actual cert.

Function to calculate R2 (R-squared) in R

Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]

# 1. 'Actual' and 'Predicted' data
df <- data.frame(
  y_actual = c(1:5),
  y_predicted  = c(0.8, 2.4, 2, 3, 4.8))

# 2. R2 Score components

# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)

# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)

# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)

# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)

# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total

iFrame Height Auto (CSS)

 <div id="content" >
    <h1>Update Information</h1>
    <div id="support-box">
        <div id="wrapper">
            <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
        </div>
    </div>
  </div>
 #support-box {
        width: 50%;
        float: left;
        display: block;
        height: 20rem; /* is support box height you can change as per your requirement*/
        background-color:#000;
    }
    #wrapper {
        width: 90%;
        display: block;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
         background:#ddd;
       margin:auto;
       height:100px; /* here the height values are automatic you can leave this if you can*/

    }
    #wrapper iframe {
        width: 100%;
        display: block;
        padding:10px;
        margin:auto;
    }

https://jsfiddle.net/umd2ahce/1/

JQuery - File attributes

Just try

var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

It worked for me

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:

out_images = np.array(X_train)[indices.astype(int)]

How to randomly select rows in SQL?

In order to shuffle the SQL result set, you need to use a database-specific function call.

Note that sorting a large result set using a RANDOM function might turn out to be very slow, so make sure you do that on small result sets.

If you have to shuffle a large result set and limit it afterward, then it's better to use something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL instead of a random function in the ORDER BY clause.

So, assuming we have the following database table:

Song database table

And the following rows in the song table:

| id | artist                          | title                              |
|----|---------------------------------|------------------------------------|
| 1  | Miyagi & ???????? ft. ??? ????? | I Got Love                         |
| 2  | HAIM                            | Don't Save Me (Cyril Hahn Remix)   |
| 3  | 2Pac ft. DMX                    | Rise Of A Champion (GalilHD Remix) |
| 4  | Ed Sheeran & Passenger          | No Diggity (Kygo Remix)            |
| 5  | JP Cooper ft. Mali-Koa          | All This Love                      |

Oracle

On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE

When running the aforementioned SQL query on Oracle, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love            |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE function call used by the ORDER BY clause.

SQL Server

On SQL Server, you need to use the NEWID function, as illustrated by the following example:

SELECT
    CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()

When running the aforementioned SQL query on SQL Server, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| JP Cooper ft. Mali-Koa - All This Love            |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |

Notice that the songs are being listed in random order, thanks to the NEWID function call used by the ORDER BY clause.

PostgreSQL

On PostgreSQL, you need to use the random function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY random()

When running the aforementioned SQL query on PostgreSQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the random function call used by the ORDER BY clause.

MySQL

On MySQL, you need to use the RAND function, as illustrated by the following example:

SELECT
  CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()

When running the aforementioned SQL query on MySQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |

Notice that the songs are being listed in random order, thanks to the RAND function call used by the ORDER BY clause.

Getting the text that follows after the regex match

You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:

System.out.println("I found the text: " + matcher.group(**1**).toString());

What is the most accurate way to retrieve a user's correct IP address in PHP?

As someone said previously, the key here is for what reason you want to store user's ips.

I'll give an example from a registration system I work on and of course the solution just to contribute sth in this old discussion that comes frequently in my searches.

Many php registration libraries use ip to throttle/lock out failed attempts based on user's ip. Consider this table:

-- mysql
DROP TABLE IF EXISTS `attempts`;
CREATE TABLE `attempts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ip` varchar(39) NOT NULL, /*<<=====*/
  `expiredate` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 -- sqlite
...

Then, when a user tries to do a login or anything related with servicing like a password reset, a function is called at the start:

public function isBlocked() {
      /*
       * used one of the above methods to capture user's ip!!!
       */
      $ip = $this->ip;
      // delete attempts from this ip with 'expiredate' in the past
      $this->deleteAttempts($ip, false);
      $query = $this->dbh->prepare("SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ?");
      $query->execute(array($ip));
      $attempts = $query->fetchColumn();
      if ($attempts < intval($this->token->get('attempts_before_verify'))) {
         return "allow";
      }
      if ($attempts < intval($this->token->get('attempts_before_ban'))) {
         return "captcha";
      }
      return "block";
   }

Say, for example, $this->token->get('attempts_before_ban') === 10 and 2 users come for the same ips as is the case in the previous codes where headers can be spoofed, then after 5 attempts each both are banned! Even worst, if all come from the same proxy then only the first 10 users will be logged and all the rest will be banned!

The critical here is that we need a unique index on table attempts and we can get it from a combination like:

 `ip` varchar(39) NOT NULL,
 `jwt_load varchar(100) NOT NULL

where jwt_load comes from a http cookie that follows the json web token technology where we store only the encrypted payload that should contain an arbitrary/unique value for every user. Of course the request should be modified to: "SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ? AND jwt_load = ?" and the class should also initiate a private $jwt.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Make sure you didn't skip all jars in

tomcat.util.scan.StandardJarScanFilter.jarsToSkip

in Tomcat catalina.properties.

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

How do I add all new files to SVN

On Alpine Linux OS I used this, based on others answers:

svn st | grep ^? | sed 's/? *//' | xargs -I fn svn add "fn"

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

How to create a zip file in Java

public static void main(String args[])
{
    omtZip("res/", "omt.zip");
}
public static void omtZip(String path,String outputFile)
{
    final int BUFFER = 2048;
    boolean isEntry = false;
    ArrayList<String> directoryList = new ArrayList<String>();
    File f = new File(path);
    if(f.exists())
    {
    try {
            FileOutputStream fos = new FileOutputStream(outputFile);
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
            byte data[] = new byte[BUFFER];

            if(f.isDirectory())
            {
               //This is Directory
                do{
                    String directoryName = "";
                    if(directoryList.size() > 0)
                    {
                        directoryName = directoryList.get(0);
                        System.out.println("Directory Name At 0 :"+directoryName);
                    }
                    String fullPath = path+directoryName;
                    File fileList = null;
                    if(directoryList.size() == 0)
                    {
                        //Main path (Root Directory)
                        fileList = f;
                    }else
                    {
                        //Child Directory
                        fileList = new File(fullPath);
                    }
                    String[] filesName = fileList.list();

                    int totalFiles = filesName.length;
                    for(int i = 0 ; i < totalFiles ; i++)
                    {
                        String name = filesName[i];
                        File filesOrDir = new File(fullPath+name);
                        if(filesOrDir.isDirectory())
                        {
                            System.out.println("New Directory Entry :"+directoryName+name+"/");
                            ZipEntry entry = new ZipEntry(directoryName+name+"/");
                            zos.putNextEntry(entry);
                            isEntry = true;
                            directoryList.add(directoryName+name+"/");
                        }else
                        {
                            System.out.println("New File Entry :"+directoryName+name);
                            ZipEntry entry = new ZipEntry(directoryName+name);
                            zos.putNextEntry(entry);
                            isEntry = true;
                            FileInputStream fileInputStream = new FileInputStream(filesOrDir);
                            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream, BUFFER);
                            int size = -1;
                            while(  (size = bufferedInputStream.read(data, 0, BUFFER)) != -1  )
                            {
                                zos.write(data, 0, size);
                            }
                            bufferedInputStream.close();
                        }
                    }
                    if(directoryList.size() > 0 && directoryName.trim().length() > 0)
                    {
                        System.out.println("Directory removed :"+directoryName);
                        directoryList.remove(0);
                    }

                }while(directoryList.size() > 0);
            }else
            {
                //This is File
                //Zip this file
                System.out.println("Zip this file :"+f.getPath());
                FileInputStream fis = new FileInputStream(f);
                BufferedInputStream bis = new BufferedInputStream(fis,BUFFER);
                ZipEntry entry = new ZipEntry(f.getName());
                zos.putNextEntry(entry);
                isEntry = true;
                int size = -1 ;
                while(( size = bis.read(data,0,BUFFER)) != -1)
                {
                    zos.write(data, 0, size);
                }
            }               

            //CHECK IS THERE ANY ENTRY IN ZIP ? ----START
            if(isEntry)
            {
              zos.close();
            }else
            {
                zos = null;
                System.out.println("No Entry Found in Zip");
            }
            //CHECK IS THERE ANY ENTRY IN ZIP ? ----START
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }else
    {
        System.out.println("File or Directory not found");
    }
 }    

}

Converting a String to a List of Words?

Personally, I think this is slightly cleaner than the answers provided

def split_to_words(sentence):
    return list(filter(lambda w: len(w) > 0, re.split('\W+', sentence))) #Use sentence.lower(), if needed

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

Ways to implement data versioning in MongoDB

The first big question when diving in to this is "how do you want to store changesets"?

  1. Diffs?
  2. Whole record copies?

My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection.

I would use the different collection to save memory space. You generally don't want a full history for a simple query. So by keeping the history out of the object you can also keep it out of the commonly accessed memory when that data is queried.

To make my life easy, I would make a history document contain a dictionary of time-stamped diffs. Something like this:

{
    _id : "id of address book record",
    changes : { 
                1234567 : { "city" : "Omaha", "state" : "Nebraska" },
                1234568 : { "city" : "Kansas City", "state" : "Missouri" }
               }
}

To make my life really easy, I would make this part of my DataObjects (EntityWrapper, whatever) that I use to access my data. Generally these objects have some form of history, so that you can easily override the save() method to make this change at the same time.

UPDATE: 2015-10

It looks like there is now a spec for handling JSON diffs. This seems like a more robust way to store the diffs / changes.

How to increase buffer size in Oracle SQL Developer to view all records?

It is easy, but takes 3 steps:

  1. In SQL Developer, enter your query in the "Worksheet" and highlight it, and press F9 to run it. The first 50 rows will be fetched into the "Query Result" window.
  2. Click on any cell in the "Query Result" window to set the focus to that window.
  3. Hold the Ctrl key and tap the "A" key.

All rows will be fetched into the "Query Result" window!

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

Getting Current date, time , day in laravel

FOR LARAVEL 5.x

I think you were looking for this

$errorLog->timestamps = false;
$errorLog->created_at = date("Y-m-d H:i:s");

remove item from stored array in angular 2

Use splice() to remove item from the array its refresh the array index to be consequence.

delete will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4

this.data.splice(this.data.indexOf(msg), 1)

How do I sort a list of dictionaries by a value of the dictionary?

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

How do I write a backslash (\) in a string?

There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

adding 30 minutes to datetime php/mysql

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);

React: "this" is undefined inside a component function

Write your function this way:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}

Fat Arrow Functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).

How to convert UTC timestamp to device local time in android

It's Working

Call this method where you use

SntpClient client = new SntpClient();
if (client.requestTime("ntp.ubuntu.com", 30000)) {
  long now = client.getNtpTime();
  Date current = new Date(now);

  date2 = sdf.parse(new Date(current.getTime()).toString());
 // System.out.println(current.toString());
  Log.e(TAG, "testing SntpClient time current.toString() "+current.toString()+" , date2 = "+date2);
}

=====================================================   

import android.os.SystemClock;
import android.util.Log;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * {@hide}
 *
 * Simple SNTP client class for retrieving network time.
 *
 * Sample usage:
 * <pre>SntpClient client = new SntpClient();
 * if (client.requestTime("time.foo.com")) {
 *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
 * }
 * </pre>
 */
public class SntpClient
{
  private static final String TAG = "SntpClient";

  private static final int REFERENCE_TIME_OFFSET = 16;
  private static final int ORIGINATE_TIME_OFFSET = 24;
  private static final int RECEIVE_TIME_OFFSET = 32;
  private static final int TRANSMIT_TIME_OFFSET = 40;
  private static final int NTP_PACKET_SIZE = 48;

  private static final int NTP_PORT = 123;
  private static final int NTP_MODE_CLIENT = 3;
  private static final int NTP_VERSION = 3;

  // Number of seconds between Jan 1, 1900 and Jan 1, 1970
  // 70 years plus 17 leap days
  private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

  // system time computed from NTP server response
  private long mNtpTime;

  // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
  private long mNtpTimeReference;

  // round trip time in milliseconds
  private long mRoundTripTime;

  /**
   * Sends an SNTP request to the given host and processes the response.
   *
   * @param host host name of the server.
   * @param timeout network timeout in milliseconds.
   * @return true if the transaction was successful.
   */
  public boolean requestTime(String host, int timeout) {
    DatagramSocket socket = null;
    try {
      socket = new DatagramSocket();
      socket.setSoTimeout(timeout);
      InetAddress address = InetAddress.getByName(host);
      byte[] buffer = new byte[NTP_PACKET_SIZE];
      DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

      // set mode = 3 (client) and version = 3
      // mode is in low 3 bits of first byte
      // version is in bits 3-5 of first byte
      buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

      // get current time and write it to the request packet
      long requestTime = System.currentTimeMillis();
      long requestTicks = SystemClock.elapsedRealtime();
      writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);

      socket.send(request);

      // read the response
      DatagramPacket response = new DatagramPacket(buffer, buffer.length);
      socket.receive(response);
      long responseTicks = SystemClock.elapsedRealtime();
      long responseTime = requestTime + (responseTicks - requestTicks);

      // extract the results
      long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
      long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
      long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
      long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
      // receiveTime = originateTime + transit + skew
      // responseTime = transmitTime + transit - skew
      // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
      //             = ((originateTime + transit + skew - originateTime) +
      //                (transmitTime - (transmitTime + transit - skew)))/2
      //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
      //             = (transit + skew - transit + skew)/2
      //             = (2 * skew)/2 = skew
      long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
      // if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
      // if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");

      // save our results - use the times on this side of the network latency
      // (response rather than request time)
      mNtpTime = responseTime + clockOffset;
      mNtpTimeReference = responseTicks;
      mRoundTripTime = roundTripTime;
    } catch (Exception e) {
      if (false) Log.d(TAG, "request time failed: " + e);
      return false;
    } finally {
      if (socket != null) {
        socket.close();
      }
    }

    return true;
  }

  /**
   * Returns the time computed from the NTP transaction.
   *
   * @return time value computed from NTP server response.
   */
  public long getNtpTime() {
    return mNtpTime;
  }

  /**
   * Returns the reference clock value (value of SystemClock.elapsedRealtime())
   * corresponding to the NTP time.
   *
   * @return reference clock corresponding to the NTP time.
   */
  public long getNtpTimeReference() {
    return mNtpTimeReference;
  }

  /**
   * Returns the round trip time of the NTP transaction
   *
   * @return round trip time in milliseconds.
   */
  public long getRoundTripTime() {
    return mRoundTripTime;
  }

  /**
   * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
   */
  private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
  }

  /**
   * Reads the NTP time stamp at the given offset in the buffer and returns
   * it as a system time (milliseconds since January 1, 1970).
   */
  private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
  }

  /**
   * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
   * at the given offset in the buffer.
   */
  private void writeTimeStamp(byte[] buffer, int offset, long time) {
    long seconds = time / 1000L;
    long milliseconds = time - seconds * 1000L;
    seconds += OFFSET_1900_TO_1970;

    // write seconds in big endian format
    buffer[offset++] = (byte)(seconds >> 24);
    buffer[offset++] = (byte)(seconds >> 16);
    buffer[offset++] = (byte)(seconds >> 8);
    buffer[offset++] = (byte)(seconds >> 0);

    long fraction = milliseconds * 0x100000000L / 1000L;
    // write fraction in big endian format
    buffer[offset++] = (byte)(fraction >> 24);
    buffer[offset++] = (byte)(fraction >> 16);
    buffer[offset++] = (byte)(fraction >> 8);
    // low order bits should be random data
    buffer[offset++] = (byte)(Math.random() * 255.0);
  }
}

How to run a method every X seconds

Here maybe helpful answer for your problem using Rx Java & Rx Android.

Best approach to remove time part of datetime in SQL Server

I think that if you stick strictly with TSQL that this is the fastest way to truncate the time:

 select convert(datetime,convert(int,convert(float,[Modified])))

I found this truncation method to be about 5% faster than the DateAdd method. And this can be easily modified to round to the nearest day like this:

select convert(datetime,ROUND(convert(float,[Modified]),0))

MySQL Workbench not opening on Windows

What works for me (workbench 64bit) is that I installed Visual Studio 2015, 2017 and 2019 here is url: https://support.microsoft.com/en-ph/help/2977003/the-latest-supported-visual-c-downloads

I installed both x86: vc_redist.x86.exe and x64: vc_redist.x64.exe

PHP file_get_contents() and setting request headers

If you don't need HTTPS and curl is not available on your system you could use fsockopen

This function opens a connection from which you can both read and write like you would do with a normal file handle.

Remove category & tag base from WordPress url - without a plugin

If you're still searching for the combination (tags, categories and pages on the url-base), you can do it like I did.

Tested using Wordpress 3.9.1

If you have pages, categories or tags having the same name, the system will take:

  1. tag
  2. page
  3. category

Phonegap Cordova installation Windows

I was having issues wtih installing phonegap. The issues were fixed when i run cmd as Administrator and then run command

npm install -g phonegap

and it is installed successfully.

Then in the directory where it is installed i opened cmd, and run command phonegap and it was working fine. Now going to play with it more :)

Thanks buddies for all this help.

How to delete a cookie?

I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:

if (document.cookie.length==0)
{
 document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;

 if (document.cookie.length==0) {alert('Cookies disabled');}
 else
 {
  document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;

  if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
  else {alert('document.cookies.length = '+document.cookies.length);}
 }
}

Multiple lines of text in UILabel

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to convert time milliseconds to hours, min, sec format in JavaScript?

I works for me as i get milliseconds=1592380675409 using javascript method getTime() which returns the number of milliseconds between midnight of January 1, 1970 and the specified date.

var d = new Date();//Wed Jun 17 2020 13:27:55 GMT+0530 (India Standard Time)
var n = d.getTime();//1592380675409 this value is store somewhere

//function call 
console.log(convertMillisecToHrMinSec(1592380675409));

var convertMillisecToHrMinSec = (time) => {
  let date = new Date(time);
  let hr = date.getHours();
  let min = date.getMinutes();
  let sec = date.getSeconds();

  hr = (hr < 10) ? "0"+ hr : hr;
  min = (min < 10) ? "0"+ min : min;
  sec = (sec < 10) ? "0"+ sec : sec;

  return hr + ':' + min + ":" + sec;//01:27:55
}

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

Checkboxes in web pages – how to make them bigger?

I tried changing the padding and margin and well as the width and height, and then finally found that if you just increase the scale it'll work:

input[type=checkbox] {
    transform: scale(1.5);
}

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

app.use(function(req, res, next) {
var allowedOrigins = [
  "http://localhost:4200"
];
var origin = req.headers.origin;
console.log(origin)
console.log(allowedOrigins.indexOf(origin) > -1)
// Website you wish to allow to
if (allowedOrigins.indexOf(origin) > -1) {
  res.setHeader("Access-Control-Allow-Origin", origin);
}

// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");

// Request methods you wish to allow
res.setHeader(
  "Access-Control-Allow-Methods",
  "GET, POST, OPTIONS, PUT, PATCH, DELETE"
);

// Request headers you wish to allow
res.setHeader(
  "Access-Control-Allow-Headers",
  "X-Requested-With,content-type,Authorization"
);

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);

// Pass to next layer of middleware
next();

});

Add this code in your index.js or server.js file and change the allowed origin array according to your requirement.

How to get the server path to the web directory in Symfony2 from inside the controller?

Since Symfony 3.3,

You can use %kernel.project_dir%/web/ instead of %kernel.root_dir%/../web/

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

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

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

Laravel Unknown Column 'updated_at'

Setting timestamps to false means you are going to lose both created_at and updated_at whereas you could set both of the keys in your model.

Case 1:

You have created_at column but not update_at you could simply set updated_at to false in your model

class ABC extends Model {

const UPDATED_AT = null;

Case 2:

You have both created_at and updated_at columns but with different column names

You could simply do:

class ABC extends Model {

const CREATED_AT = 'name_of_created_at_column';
const UPDATED_AT = 'name_of_updated_at_column';

Finally ignoring timestamps completely:

class ABC extends Model {

public $timestamps = false;

C++ convert from 1 char to string?

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

Shared-memory objects in multiprocessing

This is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.

The code would look like the following.

import numpy as np
import ray

ray.init()

@ray.remote
def func(array, param):
    # Do stuff.
    return 1

array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)

result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)

If you don't call ray.put then the array will still be stored in shared memory, but that will be done once per invocation of func, which is not what you want.

Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.

You can compare the performance of serialization in Ray versus pickle by running the following in IPython.

import numpy as np
import pickle
import ray

ray.init()

x = {i: np.ones(10**7) for i in range(20)}

# Time Ray.
%time x_id = ray.put(x)  # 2.4s
%time new_x = ray.get(x_id)  # 0.00073s

# Time pickle.
%time serialized = pickle.dumps(x)  # 2.6s
%time deserialized = pickle.loads(serialized)  # 1.9s

Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).

See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.

Using custom std::set comparator

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };
public:
    typedef std::set< T, ftor > t;
};

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

Python foreach equivalent

For an updated answer you can build a forEach function in Python easily:

def forEach(list, function):
    for i, v in enumerate(list):
        function(v, i, list)

You could also adapt this to map, reduce, filter, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.

Assigning default value while creating migration file

You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...

def change
    change_column :widgets, :colour, :string, default: 'red'
end

Bootstrap Alert Auto Close

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
         $(this).remove(); 
      });
  });

Remote debugging Tomcat with Eclipse

In the tomcat bin directory wherecatalina.bat or .sh is found (aka {CATALINA_BASE}/bin), edit (create if not there):

setenv.bat/.sh

Add the following line:

CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

That's all you need to do, you don't need to edit the catalina.bat (or .sh) file.

See the comments in catalina.bator catalina.sh.

You may have to adjust the syntax for your particular environment/situation. For example, if you already have CATALINA_OPTS defined, you might do something like this (in a windows environment):

set CATALINA_OPTS=%CATALINA_OPTS% -Xdebug -Xrunjdwp:transport=dt_socket,address=8088,server=y,suspend=n

To debug from Eclipse:

run->Debug configurations...->Remote Java Application->New

and specify a name, the project you are debugging, and the tomcat host and debug port specified above.

How can I install a .ipa file to my iPhone simulator

You can't. If it was downloaded via the iTunes store it was built for a different processor and won't work in the simulator.

android:drawableLeft margin and/or padding

Make your drawable resources.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <inset android:drawable="@drawable/small_m" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
    <item>
        <inset android:drawable="@drawable/small_p" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
</selector>

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

How do I print the type or class of a variable in Swift?

Swift 4:

// "TypeName"
func stringType(of some: Any) -> String {
    let string = (some is Any.Type) ? String(describing: some) : String(describing: type(of: some))
    return string
}

// "ModuleName.TypeName"
func fullStringType(of some: Any) -> String {
    let string = (some is Any.Type) ? String(reflecting: some) : String(reflecting: type(of: some))
    return string
}

Usage:

print(stringType(of: SomeClass()))     // "SomeClass"
print(stringType(of: SomeClass.self))  // "SomeClass"
print(stringType(of: String()))        // "String"
print(fullStringType(of: String()))    // "Swift.String"

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

PHP cURL, extract an XML response

Example:

<songs>
<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
    <artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
    <title>Kallichore</title>
    <artist>Jewitt K. Sheppard</artist>
</song>

then:

<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>

Output on your browser: Ship of Nomads

credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

HTML.ActionLink method

Use named parameters for readability and to avoid confusions.

@Html.ActionLink(
            linkText: "Click Here",
            actionName: "Action",
            controllerName: "Home",
            routeValues: new { Identity = 2577 },
            htmlAttributes: null)

Converting from a string to boolean in Python?

If you like me just need boolean from variable which is string. You can use distils as mentioned earlier by @jzwiener. However I could not import and use the module as he suggested.

Instead I end up using it this way on python3.7

distutils string to bool in python

from distutils import util # to handle str to bool conversion
enable_deletion = 'False'
enable_deletion = bool(util.strtobool(enable_deletion))

distutils is part of the python std lib so no need of installation. Which is great!

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

How to customize <input type="file">?

If you're using bootstrap here is a better solution :

<label class="btn btn-default btn-file">
    Browse <input type="file" style="display: none;" required>
</label>

For IE8 and below http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/

Source : https://stackoverflow.com/a/18164555/625952

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I'm pretty darn sure I just solved this with:

overflow-y: auto;

(Presumably just overflow: auto; would work too depending on your needs.)

Detect changed input text box

Text inputs do not fire the change event until they lose focus. Click outside of the input and the alert will show.

If the callback should fire before the text input loses focus, use the .keyup() event.

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

I have fixed it with removing below code from

C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf file

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
 </VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

And added

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot "c:/wamp/www"
    ServerName localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

And it has worked like charm

How to align text below an image in CSS?

Add a container div for the image and the caption:

<div class="item">
    <img src=""/>
    <span class="caption">Text below the image</span>
</div>

Then, with a bit of CSS, you can make an automatically wrapping image gallery:

div.item {
    vertical-align: top;
    display: inline-block;
    text-align: center;
    width: 120px;
}
img {
    width: 100px;
    height: 100px;
    background-color: grey;
}
.caption {
    display: block;
}

_x000D_
_x000D_
div.item {_x000D_
    /* To correctly align image, regardless of content height: */_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    /* To horizontally center images and caption */_x000D_
    text-align: center;_x000D_
    /* The width of the container also implies margin around the images. */_x000D_
    width: 120px;_x000D_
}_x000D_
img {_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
    /* Make the caption a block so it occupies its own line. */_x000D_
    display: block;_x000D_
}
_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/ZhLk4/1/

Updated answer

Instead of using 'anonymous' div and spans, you can also use the HTML5 figure and figcaption elements. The advantage is that these tags add to the semantic structure of the document. Visually there is no difference, but it may (positively) affect the usability and indexability of your pages.

The tags are different, but the structure of the code is exactly the same, as you can see in this updated snippet and fiddle:

<figure class="item">
    <img src=""/>
    <figcaption class="caption">Text below the image</figcaption>
</figure>

_x000D_
_x000D_
figure.item {_x000D_
    /* To correctly align image, regardless of content height: */_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    /* To horizontally center images and caption */_x000D_
    text-align: center;_x000D_
    /* The width of the container also implies margin around the images. */_x000D_
    width: 120px;_x000D_
}_x000D_
img {_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
    /* Make the caption a block so it occupies its own line. */_x000D_
    display: block;_x000D_
}
_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/ZhLk4/379/

How to set scope property with ng-init?

Just set ng-init as a function. You should not have to use watch.

<body ng-controller="MainCtrl" ng-init="init()">
  <div ng-init="init('Blah')">{{ testInput }}</div>
</body>

app.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.testInput = null;
  $scope.init = function(value) {
    $scope.testInput= value;
  }
}]);

Here's an example.

Plunker

Converts scss to css

Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler

Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;

e.g sass mda/at-md-black.scss:css/at-md-black.css;

What is the difference between cache and persist?

For impatient:

Same

Without passing argument, persist() and cache() are the same, with default settings:

  • when RDD: MEMORY_ONLY
  • when Dataset: MEMORY_AND_DISK

Difference:

Unlike cache(), persist() allows you to pass argument inside the bracket, in order to specify the level:

  • persist(MEMORY_ONLY)
  • persist(MEMORY_ONLY_SER)
  • persist(MEMORY_AND_DISK)
  • persist(MEMORY_AND_DISK_SER )
  • persist(DISK_ONLY )

Voilà!

How to use concerns in Rails 4

It's worth to mention that using concerns is considered bad idea by many.

  1. like this guy
  2. and this one

Some reasons:

  1. There is some dark magic happening behind the scenes - Concern is patching include method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.
  2. Your classes are no less dry. If you stuff 50 public methods in various modules and include them, your class still has 50 public methods, it's just that you hide that code smell, sort of put your garbage in the drawers.
  3. Codebase is actually harder to navigate with all those concerns around.
  4. Are you sure all members of your team have same understanding what should really substitute concern?

Concerns are easy way to shoot yourself in the leg, be careful with them.

Reading an Excel file in PHP

Try this...

I have used following code to read "xls and xlsx"

    <?php
    include 'excel_reader.php';       // include the class
    $excel = new PhpExcelReader;      // creates object instance of the class
    $excel->read('excel_file.xls');   // reads and stores the excel file data

    // Test to see the excel data stored in $sheets property
    echo '<pre>';
    var_export($excel->sheets);

    echo '</pre>';

    or 

 echo '<pre>';
    print_r($excel->sheets);

    echo '</pre>';

Reference:http://coursesweb.net/php-mysql/read-excel-file-data-php_pc

How to save .xlsx data to file as a blob

I've found a solution worked for me:

const handleDownload = async () => {
   const req = await axios({
     method: "get",
     url: `/companies/${company.id}/data`,
     responseType: "blob",
   });
   var blob = new Blob([req.data], {
     type: req.headers["content-type"],
   });
   const link = document.createElement("a");
   link.href = window.URL.createObjectURL(blob);
   link.download = `report_${new Date().getTime()}.xlsx`;
   link.click();
 };

I just point a responseType: "blob"

Java - How to access an ArrayList of another class?

import java.util.ArrayList;
public class numbers {
   private int number1 = 50;
   private int number2 = 100;
   private List<Integer> list;

   public numbers() {
       list = new ArrayList<Integer>();
       list.add(number1);
       list.add(number2);
   }

   public List<Integer> getList() {
       return list;
   }
}

And the test class:

import java.util.ArrayList;
public class test {
   private numbers number;

   //example
   public test() {
     number = new numbers();
     List<Integer> list = number.getList();
     //hurray !
   }
}

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Pass Multiple Parameters to jQuery ajax call

Its all about data which you pass; has to properly formatted string. If you are passing empty data then data: {} will work. However with multiple parameters it has to be properly formatted e.g.

var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' +  '}';

....

data : dataParam

...

Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.

How to make an input type=button act like a hyperlink and redirect using a get request?

For those who stumble upon this from a search (Google) and are trying to translate to .NET and MVC code. (as in my case)

@using (Html.BeginForm("RemoveLostRolls", "Process", FormMethod.Get)) {
     <input type="submit" value="Process" />
}

This will show a button labeled "Process" and take you to "/Process/RemoveLostRolls". Without "FormMethod.Get" it worked, but was seen as a "post".

How to get an MD5 checksum in PowerShell

There are a lot of examples online using ComputeHash(). My testing showed this was very slow when running over a network connection. The snippet below runs much faster for me, however your mileage may vary:

$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = New-Object byte[] (1024*1024*8) # 8 MB buffer
while (($read_len = $fd.Read($buf,0,$buf.length)) -eq $buf.length){
    $total += $buf.length
    $md5.TransformBlock($buf,$offset,$buf.length,$buf,$offset)
    Write-Progress -Activity "Hashing File" `
       -Status $file -percentComplete ($total/$fd.length * 100)
}

# Finalize the last read
$md5.TransformFinalBlock($buf, 0, $read_len)
$hash = $md5.Hash

# Convert hash bytes to a hexadecimal formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
Write-Host $hash_txt

How do I convert Int/Decimal to float in C#?

You can just do a cast

int val1 = 1;
float val2 = (float)val1;

or

decimal val3 = 3;
float val4 = (float)val3;

dispatch_after - GCD in Swift?

Now more than syntactic sugar for asynchronous dispatches in Grand Central Dispatch (GCD) in Swift.

add Podfile

pod 'AsyncSwift'

Then,you can use it like this.

let seconds = 3.0
Async.main(after: seconds) {
print("Is called after 3 seconds")
}.background(after: 6.0) {
print("At least 3.0 seconds after previous block, and 6.0 after Async code is called")
}

How to specify table's height such that a vertical scroll bar appears?

You need to wrap the table inside another element and set the height of that element. Example with inline css:

<div style="height: 500px; overflow: auto;">
 <table>
 </table>
</div>

How to search for occurrences of more than one space between words in a line

[ ]{2,}

SPACE (2 or more)

You could also check that before and after those spaces words follow. (not other whitespace like tabs or new lines)

\w[ ]{2,}\w

the same, but you can also pick (capture) only the spaces for tasks like replacement

\w([ ]{2,})\w

or see that before and after spaces there is anything, not only word characters (except whitespace)

[^\s]([ ]{2,})[^\s]

Confirm deletion using Bootstrap 3 modal box

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/

How do I put text on ProgressBar?

I wold create a control named for example InfoProgresBar, that provide this functionality with a label or two (Main Job, Current Job) and ProgressBar and use it instead of that ProgressBar.

How to add action listener that listens to multiple buttons

I'm amazed that nobody has mentioned using an action command. This is a pretty standard way of associating sources and listeners. Its really useful if;

  • you have multiple event sources that need to do the same thing (eg if you want the use to be able to press the enter key on a text field as an alternative to clicking a button next to it)
  • you don't have a ref to the component generating the event

see;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;    
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DontExtendJFrame implements ActionListener {

  private enum Actions {
    HELLO,
    GOODBYE
  }

  public static void main(String[] args) {

    DontExtendJFrame instance = new DontExtendJFrame();

    JFrame frame = new JFrame("Test");
    frame.setLayout(new FlowLayout());
    frame.setSize(200, 100);

    JButton hello = new JButton("Hello");
    hello.setActionCommand(Actions.HELLO.name());
    hello.addActionListener(instance);
    frame.add(hello);

    JButton goodbye = new JButton("Goodbye");
    goodbye.setActionCommand(Actions.GOODBYE.name());
    goodbye.addActionListener(instance);
    frame.add(goodbye);

    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    if (evt.getActionCommand() == Actions.HELLO.name()) {
      JOptionPane.showMessageDialog(null, "Hello");
    } else if (evt.getActionCommand() == Actions.GOODBYE.name()) {
      JOptionPane.showMessageDialog(null, "Goodbye");
    }
  }
}

Jquery submit form

If you have only 1 form in you page, use this. You do not need to know id or name of the form. I just used this code - working:

document.forms[0].submit();

Linq style "For Each"

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}

Where should I put <script> tags in HTML markup?

The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute js code.

<script> ... your code here ... </script>
</body>

And if you write in JQuery the following can be in the head document and it will execute after the document loads:

<script>
$(document).ready(function(){
   //your code here...
});
</script>

How to get a List<string> collection of values from app.config in WPF?

Had the same problem, but solved it in a different way. It might not be the best solution, but its a solution.

in app.config:

<add key="errorMailFirst" value="[email protected]"/>
<add key="errorMailSeond" value="[email protected]"/>

Then in my configuration wrapper class, I add a method to search keys.

        public List<string> SearchKeys(string searchTerm)
        {
            var keys = ConfigurationManager.AppSettings.Keys;
            return keys.Cast<object>()
                       .Where(key => key.ToString().ToLower()
                       .Contains(searchTerm.ToLower()))
                       .Select(key => ConfigurationManager.AppSettings.Get(key.ToString())).ToList();
        }

For anyone reading this, i agree that creating your own custom configuration section is cleaner, and more secure, but for small projects, where you need something quick, this might solve it.

What is the use of the @Temporal annotation in Hibernate?

If you're looking for short answer:

In the case of using java.util.Date, Java doesn't really know how to directly relate to SQL types. This is when @Temporal comes into play. It's used to specify the desired SQL type.

Source: Baeldung

How to list all files in a directory and its subdirectories in hadoop hdfs

don't use recursive approach (heap issues) :) use a queue

queue.add(param_dir)
while (queue is not empty){

  directory=  queue.pop
 - get items from current directory
 - if item is file add to a list (final list)
 - if item is directory => queue.push
}

that was easy, enjoy!

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

You better install Ruby 2.2.5 for compatibility. The Ruby version in your local machine is different from the one declared in Gemfile.

If you're using rvm:

rvm install 2.2.5
rvm use 2.2.5

else if you're using rbenv:

rbenv install 2.2.5
rbenv local 2.2.5

else if you can not change ruby version by rbenv, read here

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

How do I run a Python program in the Command Prompt in Windows 7?

Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

cmd

Go to the directory you installed Python in

cd C:\Python27

Run python and the win_add2path.py script in Tools\Scripts

python.exe Tools\Scripts\win_add2path.py

Now you can use python as a command anywhere.

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

Start with root user or with sudo, it works fine, here is sample output:

[ec2-user@ip-172-31-12-164 ~]$ service httpd start
Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:80
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
                                                           **[FAILED]**
[ec2-user@ip-172-31-12-164 ~]$ sudo service httpd start
Starting httpd:                                            [  OK  ]
[ec2-user@ip-172-31-12-164 ~]$ sudo service httpd status
httpd (pid  3077) is running...

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

What is a NullPointerException, and how do I fix it?

When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign the value of 10 on the second line, your value of 10 is written into the memory location referred to by x.

But, when you try to declare a reference type, something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing".

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the pointer variable num is assigned to that Integer object.

The NullPointerException (NPE) occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.

Dereferencing usually happens when using . to access a method or field, or using [ to index an array.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. The following is 2 minutes read to understand this amazing language feature.

https://jfeatures.com/blog/NullPointerException

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Convert StreamReader to byte[]

Just throw everything you read into a MemoryStream and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    var buffer = new byte[512];
    var bytesRead = default(int);
    while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
        memstream.Write(buffer, 0, bytesRead);
    bytes = memstream.ToArray();
}

Or if you don't want to manage the buffers:

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek

How to remove a package from Laravel using composer?

In case the given answers still don't help you remove that, try this:

  • Manually delete the line in require from composer.json

  • Run composer update

How to change font size in html?

If you're just interested in increasing the font size of just the first paragraph of any document, an effect used by online publications, then you can use the first-child pseudo-class to achieve the desired effect.

p:first-child
{
   font-size:   115%; // Will set the font size to be 115% of the original font-size for the p element.
}

However, this will change the font size of every p element that is the first-child of any other element. If you're interested in setting the size of the first p element of the body element, then use the following:

body > p:first-child
{
   font-size:   115%;
}

The above code will only work with the p element that is a child of the body element.

Join vs. sub-query

MySQL version: 5.5.28-0ubuntu0.12.04.2-log

I was also under the impression that JOIN is always better than a sub-query in MySQL, but EXPLAIN is a better way to make a judgment. Here is an example where sub queries work better than JOINs.

Here is my query with 3 sub-queries:

EXPLAIN SELECT vrl.list_id,vrl.ontology_id,vrl.position,l.name AS list_name, vrlih.position AS previous_position, vrl.moved_date 
FROM `vote-ranked-listory` vrl 
INNER JOIN lists l ON l.list_id = vrl.list_id 
INNER JOIN `vote-ranked-list-item-history` vrlih ON vrl.list_id = vrlih.list_id AND vrl.ontology_id=vrlih.ontology_id AND vrlih.type='PREVIOUS_POSITION' 
INNER JOIN list_burial_state lbs ON lbs.list_id = vrl.list_id AND lbs.burial_score < 0.5 
WHERE vrl.position <= 15 AND l.status='ACTIVE' AND l.is_public=1 AND vrl.ontology_id < 1000000000 
 AND (SELECT list_id FROM list_tag WHERE list_id=l.list_id AND tag_id=43) IS NULL 
 AND (SELECT list_id FROM list_tag WHERE list_id=l.list_id AND tag_id=55) IS NULL 
 AND (SELECT list_id FROM list_tag WHERE list_id=l.list_id AND tag_id=246403) IS NOT NULL 
ORDER BY vrl.moved_date DESC LIMIT 200;

EXPLAIN shows:

+----+--------------------+----------+--------+-----------------------------------------------------+--------------+---------+-------------------------------------------------+------+--------------------------+
| id | select_type        | table    | type   | possible_keys                                       | key          | key_len | ref                                             | rows | Extra                    |
+----+--------------------+----------+--------+-----------------------------------------------------+--------------+---------+-------------------------------------------------+------+--------------------------+
|  1 | PRIMARY            | vrl      | index  | PRIMARY                                             | moved_date   | 8       | NULL                                            |  200 | Using where              |
|  1 | PRIMARY            | l        | eq_ref | PRIMARY,status,ispublic,idx_lookup,is_public_status | PRIMARY      | 4       | ranker.vrl.list_id                              |    1 | Using where              |
|  1 | PRIMARY            | vrlih    | eq_ref | PRIMARY                                             | PRIMARY      | 9       | ranker.vrl.list_id,ranker.vrl.ontology_id,const |    1 | Using where              |
|  1 | PRIMARY            | lbs      | eq_ref | PRIMARY,idx_list_burial_state,burial_score          | PRIMARY      | 4       | ranker.vrl.list_id                              |    1 | Using where              |
|  4 | DEPENDENT SUBQUERY | list_tag | ref    | list_tag_key,list_id,tag_id                         | list_tag_key | 9       | ranker.l.list_id,const                          |    1 | Using where; Using index |
|  3 | DEPENDENT SUBQUERY | list_tag | ref    | list_tag_key,list_id,tag_id                         | list_tag_key | 9       | ranker.l.list_id,const                          |    1 | Using where; Using index |
|  2 | DEPENDENT SUBQUERY | list_tag | ref    | list_tag_key,list_id,tag_id                         | list_tag_key | 9       | ranker.l.list_id,const                          |    1 | Using where; Using index |
+----+--------------------+----------+--------+-----------------------------------------------------+--------------+---------+-------------------------------------------------+------+--------------------------+

The same query with JOINs is:

EXPLAIN SELECT vrl.list_id,vrl.ontology_id,vrl.position,l.name AS list_name, vrlih.position AS previous_position, vrl.moved_date 
FROM `vote-ranked-listory` vrl 
INNER JOIN lists l ON l.list_id = vrl.list_id 
INNER JOIN `vote-ranked-list-item-history` vrlih ON vrl.list_id = vrlih.list_id AND vrl.ontology_id=vrlih.ontology_id AND vrlih.type='PREVIOUS_POSITION' 
INNER JOIN list_burial_state lbs ON lbs.list_id = vrl.list_id AND lbs.burial_score < 0.5 
LEFT JOIN list_tag lt1 ON lt1.list_id = vrl.list_id AND lt1.tag_id = 43 
LEFT JOIN list_tag lt2 ON lt2.list_id = vrl.list_id AND lt2.tag_id = 55 
INNER JOIN list_tag lt3 ON lt3.list_id = vrl.list_id AND lt3.tag_id = 246403 
WHERE vrl.position <= 15 AND l.status='ACTIVE' AND l.is_public=1 AND vrl.ontology_id < 1000000000 
AND lt1.list_id IS NULL AND lt2.tag_id IS NULL 
ORDER BY vrl.moved_date DESC LIMIT 200;

and the output is:

+----+-------------+-------+--------+-----------------------------------------------------+--------------+---------+---------------------------------------------+------+----------------------------------------------+
| id | select_type | table | type   | possible_keys                                       | key          | key_len | ref                                         | rows | Extra                                        |
+----+-------------+-------+--------+-----------------------------------------------------+--------------+---------+---------------------------------------------+------+----------------------------------------------+
|  1 | SIMPLE      | lt3   | ref    | list_tag_key,list_id,tag_id                         | tag_id       | 5       | const                                       | 2386 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | l     | eq_ref | PRIMARY,status,ispublic,idx_lookup,is_public_status | PRIMARY      | 4       | ranker.lt3.list_id                          |    1 | Using where                                  |
|  1 | SIMPLE      | vrlih | ref    | PRIMARY                                             | PRIMARY      | 4       | ranker.lt3.list_id                          |  103 | Using where                                  |
|  1 | SIMPLE      | vrl   | ref    | PRIMARY                                             | PRIMARY      | 8       | ranker.lt3.list_id,ranker.vrlih.ontology_id |   65 | Using where                                  |
|  1 | SIMPLE      | lt1   | ref    | list_tag_key,list_id,tag_id                         | list_tag_key | 9       | ranker.lt3.list_id,const                    |    1 | Using where; Using index; Not exists         |
|  1 | SIMPLE      | lbs   | eq_ref | PRIMARY,idx_list_burial_state,burial_score          | PRIMARY      | 4       | ranker.vrl.list_id                          |    1 | Using where                                  |
|  1 | SIMPLE      | lt2   | ref    | list_tag_key,list_id,tag_id                         | list_tag_key | 9       | ranker.lt3.list_id,const                    |    1 | Using where; Using index                     |
+----+-------------+-------+--------+-----------------------------------------------------+--------------+---------+---------------------------------------------+------+----------------------------------------------+

A comparison of the rows column tells the difference and the query with JOINs is using Using temporary; Using filesort.

Of course when I run both the queries, the first one is done in 0.02 secs, the second one does not complete even after 1 min, so EXPLAIN explained these queries properly.

If I do not have the INNER JOIN on the list_tag table i.e. if I remove

AND (SELECT list_id FROM list_tag WHERE list_id=l.list_id AND tag_id=246403) IS NOT NULL  

from the first query and correspondingly:

INNER JOIN list_tag lt3 ON lt3.list_id = vrl.list_id AND lt3.tag_id = 246403

from the second query, then EXPLAIN returns the same number of rows for both queries and both these queries run equally fast.

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

Could you explain STA and MTA?

As my understanding, the 'Apartment' is used to protect the COM objects from multi-threading issues.

If a COM object is not thread-safe, it should declare it as a STA object. Then only the thread who creates it can access it. The creation thread should declare itself as a STA thread. Under the hood, the thread stores the STA information in its TLS(Thread Local Storage). We call this behavior as that the thread enters a STA apartment. When other threads want to access this COM object, it should marshal the access to the creation thread. Basically, the creation thread uses messages mechanism to process the in-bound calls.

If a COM object is thread-safe, it should declare it as a MTA object. The MTA object can be accessed by multi-threads.

How to change legend size with matplotlib.pyplot

There are multiple settings for adjusting the legend size. The two I find most useful are:

  • labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, legend(..., labelspacing=0.2) will reduce the spacing between entries to 2 points. The default on my install is about 0.5.
  • prop: which allows full control of the font size, etc. You can set an 8 point font using legend(..., prop={'size':8}). The default on my install is about 14 points.

In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad, handlelength, handletextpad, borderaxespad, and columnspacing. These all follow the same form as labelspacing and area also in multiples of fontsize.

These values can also be set as the defaults for all figures using the matplotlibrc file.

How can I pair socks from a pile efficiently?

We can use hashing to our leverage if you can abstract a single pair of socks as the key itself and its other pair as value.

  1. Make two imaginary sections behind you on the floor, one for you and another for your spouse.

  2. Take one from the pile of socks.

  3. Now place the socks on the floor, one by one, following the below rule.

    • Identify the socks as yours or hers and look at the relevant section on the floor.

    • If you can spot the pair on the floor pick it up and knot them up or clip them up or do whatever you would do after you find a pair and place it in a basket (remove it from the floor).

    • Place it in the relevant section.

  4. Repeat 3 until all socks are over from the pile.


Explanation:

Hashing and Abstraction

Abstraction is a very powerful concept that has been used to improve user experience (UX). Examples of abstraction in real-life interactions with computers include:

  • Folder icons used for navigation in a GUI (graphical user interface) to access an address instead of typing the actual address to navigate to a location.
  • GUI sliders used to control various levels of volume, document scroll position, etc..

Hashing or other not-in-place solutions are not an option because I am not able to duplicate my socks (though it could be nice if I could).

I believe the asker was thinking of applying hashing such that the slot to which either pair of sock goes should be known before placing them.

That's why I suggested abstracting a single sock that is placed on the floor as the hash key itself (hence there is no need to duplicate the socks).

How to define our hash key?

The below definition for our key would also work if there are more than one pair of similar socks. That is, let's say there are two pairs of black men socks PairA and PairB, and each sock is named PairA-L, PairA-R, PairB-L, PairB-R. So PairA-L can be paired with PairB-R, but PairA-L and PairB-L cannot be paired.

Let say any sock can be uniqly identified by,

Attribute[Gender] + Attribute[Colour] + Attribute[Material] + Attribute[Type1] + Attribute[Type2] + Attribute[Left_or_Right]

This is our first hash function. Let's use a short notation for this h1(G_C_M_T1_T2_LR). h1(x) is not our location key.

Another hash function eliminating the Left_or_Right attribute would be h2(G_C_M_T1_T2). This second function h2(x) is our location key! (for the space on the floor behind you).

  • To locate the slot, use h2(G_C_M_T1_T2).
  • Once the slot is located then use h1(x) to check their hashes. If they don't match, you have a pair. Else throw the sock into the same slot.

NOTE: Since we remove a pair once we find one, it's safe to assume that there would only be at a maximum one slot with a unique h2(x) or h1(x) value.

In case we have each sock with exactly one matching pair then use h2(x) for finding the location and if no pair, a check is required, since it's safe to assume they are a pair.

Why is it important to lay the socks on the floor

Let's consider a scenario where the socks are stacked over one another in a pile (worst case). This means we would have no other choice but to do a linear search to find a pair.

Spreading them on the floor gives more visibility which improves the chance of spotting the matching sock (matching a hash key). When a sock was placed on the floor in step 3, our mind had subconsciously registered the location. - So in case, this location is available in our memory we can directly find the matching pair. - In case the location is not remembered, don't worry, then we can always revert back to linear search.

Why is it important to remove the pair from the floor?

  • Short-term human memory works best when it has fewer items to remember. Thus increasing the probability of us resorting to hashing to spot the pair.
  • It will also reduce the number of items to be searched through when linear searching for the pair is being used.

Analysis

  1. Case 1: Worst case when Derpina cannot remember or spot the socks on the floor directly using the hashing technique. Derp does a linear search through the items on the floor. This is not worse than the iterating through the pile to find the pair.
    • Upper bound for comparison: O(n^2).
    • Lower bound for comparison: (n/2). (when every other sock Derpina picks up is the pair of previous one).
  2. Case 2: Derp remembers each the location of every sock that he placed on the floor and each sock has exactly one pair.
    • Upper bound for comparison: O(n/2).
    • Lower bound for comparison: O(n/2).

I am talking about comparison operations, picking the socks from the pile would necessarily be n number of operations. So a practical lower bound would be n iterations with n/2 comparisons.

Speeding up things

To achieve a perfect score so Derp gets O(n/2) comparisons, I would recommend Derpina to,

  • spend more time with the socks to get familiarize with it. Yes, that means spending more time with Derp's socks too.
  • Playing memory games like spot the pairs in a grid can improve short-term memory performance, which can be highly beneficial.

Is this equivalent to the element distinctness problem?

The method I suggested is one of the methods used to solve element distinctness problem where you place them in the hash table and do the comparison.

Given your special case where there exists only one exact pair, it has become very much equivalent to the element distinct problem. Since we can even sort the socks and check adjacent socks for pairs (another solution for EDP).

However, if there is a possibility of more than one pair that can exist for given sock then it deviates from EDP.

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!

How to get all table names from a database?

public static ArrayList<String> getTablesList(Connection conn)
            throws SQLException {

        ArrayList<String> listofTable = new ArrayList<String>();

        DatabaseMetaData md = conn.getMetaData();

        ResultSet rs = md.getTables(null, null, "%", null);

        while (rs.next()) {
            if (rs.getString(4).equalsIgnoreCase("TABLE")) {
                listofTable.add(rs.getString(3));
            }
        }
        return listofTable;
    }

ModelState.AddModelError - How can I add an error that isn't for a property?

You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);

LPCSTR, LPCTSTR and LPTSTR

The short answer to 2nd part of the question is simply that CString class doesn't provide a direct typecast conversion by design and what you are doing is kind of cheat.

A longer answer is the following:

The reason you can typcast CString to LPCTSTR is because CString provides this facility by overriding operator=. By design it provides conversion to only LPCTSTR pointer so the string value can't be modified with this pointer.

In other words, it simply doesn't provide an overload operator= to convert the CString into LPSTR for the same reason as above. They don't want to allow altering the string value this way.

So essentially, the trick is to use the operator CString provide and get this:

LPTSTR lptstr = (LPCTSTR) string; // CString provide this operator overload

Now LPTSTR can be further type casted to LPSTR :)

dispinfo.item.pszText = LPTSTR( lpfzfd); // accomplish the cheat :P

The correct way to get LPTSTR from 'CString' is this though (complete example):

CString str = _T("Hello");
LPTSTR lpstr = str.GetBuffer(str.GetAllocLength());
str.ReleaseBuffer(); // you must call this function if you change the string above with the pointer

Again because the GetBuffer() returns LPTSTR for that reason that now you can modify :)

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

Consider this:

std::string str = "Hello " + "world"; // bad!

Both the rhs and the lhs for operator + are char*s. There is no definition of operator + that takes two char*s (in fact, the language doesn't permit you to write one). As a result, on my compiler this produces a "cannot add two pointers" error (yours apparently phrases things in terms of arrays, but it's the same problem).

Now consider this:

std::string str = "Hello " + std::string("world"); // ok

There is a definition of operator + that takes a const char* as the lhs and a std::string as the rhs, so now everyone is happy.

You can extend this to as long a concatenation chain as you like. It can get messy, though. For example:

std::string str = "Hello " + "there " + std::string("world"); // no good!

This doesn't work because you are trying to + two char*s before the lhs has been converted to std::string. But this is fine:

std::string str = std::string("Hello ") + "there " + "world"; // ok

Because once you've converted to std::string, you can + as many additional char*s as you want.

If that's still confusing, it may help to add some brackets to highlight the associativity rules and then replace the variable names with their types:

((std::string("Hello ") + "there ") + "world");
((string + char*) + char*)

The first step is to call string operator+(string, char*), which is defined in the standard library. Replacing those two operands with their result gives:

((string) + char*)

Which is exactly what we just did, and which is still legal. But try the same thing with:

((char* + char*) + string)

And you're stuck, because the first operation tries to add two char*s.

Moral of the story: If you want to be sure a concatenation chain will work, just make sure one of the first two arguments is explicitly of type std::string.

How to convert ActiveRecord results into an array of hashes

May be?

result.map(&:attributes)

If you need symbols keys:

result.map { |r| r.attributes.symbolize_keys }

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

Best way to check if a URL is valid

function is_url($uri){
    if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){
      return $uri;
    }
    else{
        return false;
    }
}

Is it possible to have a multi-line comments in R?

CTRL+SHIFT+C in Eclipse + StatET and Rstudio.

How to use SortedMap interface in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

GitHub: invalid username or password

Disabling 2 factor authentication at github worked for me.

I see that there is a deleted answer that says this, with the deletion reason as "does not answer the question". If it works, then I think it answers the question...

Android: textview hyperlink

You could have two separate TextViews and you could align them accordingly in your layout if needed:

    Text1.setText(
        Html.fromHtml(
            "<a href=\"http://www.google.com\">google</a> "));
    Text1.setMovementMethod(LinkMovementMethod.getInstance());

    Text2.setText(
            Html.fromHtml(
                "<a href=\"http://www.stackoverflow.com\">stackoverflow</a> "));
    Text2.setMovementMethod(LinkMovementMethod.getInstance());

Then if you want to strip the "link underline". Create a class:

public class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String url) {
        super(url);
    }
    @Override public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
        }
}

Then add this method in your main Activity class where you have the TextViews

private void stripUnderlines(TextView textView) {
    Spannable s = new SpannableString(textView.getText());
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span: spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}

And then just call this after you initialised the TextViews (in your onCreate):

stripUnderlines(Text1);
stripUnderlines(Text2);

Circular (or cyclic) imports in Python

Module a.py :

import b
print("This is from module a")

Module b.py

import a
print("This is from module b")

Running "Module a" will output:

>>> 
'This is from module a'
'This is from module b'
'This is from module a'
>>> 

It output this 3 lines while it was supposed to output infinitival because of circular importing. What happens line by line while running"Module a" is listed here:

  1. The first line is import b. so it will visit module b
  2. The first line at module b is import a. so it will visit module a
  3. The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a".
  4. After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b"
  5. Module b lines are executed completely. so we will go back to module a where we started module b.
  6. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.

Measure execution time for a Java method

As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself

long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization 
long start2 = System.nanoTime();
myCall(); 
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;

System.out.println(diff + " ns");

By the way, you will measure different values for the same call due to

  • other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
  • cache fillings (cold, warm)
  • jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))

Call async/await functions in parallel

TL;DR

Use Promise.all for the parallel function calls, the answer behaviors not correctly when the error occurs.


First, execute all the asynchronous calls at once and obtain all the Promise objects. Second, use await on the Promise objects. This way, while you wait for the first Promise to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:

// Begin first call and store promise without waiting
const someResult = someCall();

// Begin second call and store promise without waiting
const anotherResult = anotherCall();

// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];

// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise

JSbin example: http://jsbin.com/xerifanima/edit?js,console

Caveat: It doesn't matter if the await calls are on the same line or on different lines, so long as the first await call happens after all of the asynchronous calls. See JohnnyHK's comment.


Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed. I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()]), check the following code snippet

_x000D_
_x000D_
const correctAsync500ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 500, 'correct500msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 100, 'correct100msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    setTimeout(reject, 100, 'reject100msError');_x000D_
  });_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
  const label = 'test async functions in array';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    const p1 = fun1();_x000D_
    const p2 = fun2();_x000D_
    const result = [await p1, await p2];_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
  const label = 'test async functions with Promise.all';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
  console.group('async functions without error');_x000D_
  console.log('async functions without error: start')_x000D_
  await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
  console.groupEnd();_x000D_
_x000D_
  console.group('async functions with error');_x000D_
  console.log('async functions with error: start')_x000D_
  await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
  console.groupEnd();_x000D_
})();
_x000D_
_x000D_
_x000D_

How to disable the ability to select in a DataGridView?

Enabled property to false

or

this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;

fs: how do I locate a parent folder?

Try this:

fs.readFile(__dirname + '/../../foo.bar');

Note the forward slash at the beginning of the relative path.

SQL Server 2008: How to query all databases sizes?

All this examples work fine on most of my database servers. However if you have 1 server with multiple instances and all those servers those query's give you no result.

For instance the first query gives a result like:

name    DataFileSizeMB  LogFileSizeMB
master  NULL    NULL
tempdb  NULL    NULL
model   NULL    NULL
msdb    NULL    NULL

So the databases are selected from sys.databases, however the table sys.master_files seems to be empty or gives no result.

Even a simple query as select * from sys.master_files has a result of 0 records. You don't receive any errors but no records are found. On my servers with only 1 database instance this works fine.

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

MyStore.js

const store = createStore(myReducer);
export store;

or

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

or if you used default

import store from './MyStore'
store.dispatch(...)

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

How to download a branch with git?

Thanks to a related question, I found out that I need to "checkout" the remote branch as a new local branch, and specify a new local branch name.

git checkout -b newlocalbranchname origin/branch-name

Or you can do:

git checkout -t origin/branch-name

The latter will create a branch that is also set to track the remote branch.


Update: It's been 5 years since I originally posted this question. I've learned a lot and git has improved since then. My usual workflow is a little different now.

If I want to fetch the remote branches, I simply run:

git pull

This will fetch all of the remote branches and merge the current branch. It will display an output that looks something like this:

From github.com:andrewhavens/example-project
   dbd07ad..4316d29  master     -> origin/master
 * [new branch]      production -> origin/production
 * [new branch]      my-bugfix-branch -> origin/my-bugfix-branch
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 4316d296c55ac2e13992a22161fc327944bcf5b8.

Now git knows about my new my-bugfix-branch. To switch to this branch, I can simply run:

git checkout my-bugfix-branch

Normally, I would need to create the branch before I could check it out, but in newer versions of git, it's smart enough to know that you want to checkout a local copy of this remote branch.

laravel 5.4 upload image

This code will store the image in database.

$('#image').change(function(){
        // FileReader function for read the file.
        let reader = new FileReader();
        var base64;
        reader.readAsDataURL(this.files[0]); 

        //Read File
        let filereader = new FileReader();
        var selectedFile = this.files[0];

        // Onload of file read the file content
        filereader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            $("#pimage").val(JSON.stringify(base64));
        };

        filereader.readAsDataURL(selectedFile); 
 });

HTML content should be like this.

<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
        <input id="image" type="file" class="inputMaterial" name="image">        
        <input type="hidden" id="pimage" name="pimage" value="">
        <span class="bar"></span>
    </div>

Store image data in database like this:

//property_image longtext(database field type)

 $data= array(
      'property_image' => trim($request->get('pimage'),'"')
 );

Display image:

<img src="{{$result->property_image}}" >

Password hash function for Excel VBA

Here is the MD5 code inserted in an Excel Module with the name "module_md5":

    Private Const BITS_TO_A_BYTE = 8
    Private Const BYTES_TO_A_WORD = 4
    Private Const BITS_TO_A_WORD = 32

    Private m_lOnBits(30)
    Private m_l2Power(30)

    Sub SetUpArrays()
        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)
    End Sub

    Private Function LShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            LShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And 1 Then
                LShift = &H80000000
            Else
                LShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        If (lValue And m_l2Power(31 - iShiftBits)) Then
            LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
        Else
            LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
        End If
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    Private Function RotateLeft(lValue, iShiftBits)
        RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
    End Function

    Private Function AddUnsigned(lX, lY)
        Dim lX4
        Dim lY4
        Dim lX8
        Dim lY8
        Dim lResult

        lX8 = lX And &H80000000
        lY8 = lY And &H80000000
        lX4 = lX And &H40000000
        lY4 = lY And &H40000000

        lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)

        If lX4 And lY4 Then
            lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
        ElseIf lX4 Or lY4 Then
            If lResult And &H40000000 Then
                lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
            Else
                lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
            End If
        Else
            lResult = lResult Xor lX8 Xor lY8
        End If

        AddUnsigned = lResult
    End Function

    Private Function F(x, y, z)
        F = (x And y) Or ((Not x) And z)
    End Function

    Private Function G(x, y, z)
        G = (x And z) Or (y And (Not z))
    End Function

    Private Function H(x, y, z)
        H = (x Xor y Xor z)
    End Function

    Private Function I(x, y, z)
        I = (y Xor (x Or (Not z)))
    End Function

    Private Sub FF(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub GG(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub HH(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub II(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Function ConvertToWordArray(sMessage)
        Dim lMessageLength
        Dim lNumberOfWords
        Dim lWordArray()
        Dim lBytePosition
        Dim lByteCount
        Dim lWordCount

        Const MODULUS_BITS = 512
        Const CONGRUENT_BITS = 448

        lMessageLength = Len(sMessage)

        lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
        ReDim lWordArray(lNumberOfWords - 1)

        lBytePosition = 0
        lByteCount = 0
        Do Until lByteCount >= lMessageLength
            lWordCount = lByteCount \ BYTES_TO_A_WORD
            lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
            lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
            lByteCount = lByteCount + 1
        Loop

        lWordCount = lByteCount \ BYTES_TO_A_WORD
        lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE

        lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)

        lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
        lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)

        ConvertToWordArray = lWordArray
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
            WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
        Next
    End Function

    Public Function MD5(sMessage)

        module_md5.SetUpArrays

        Dim x
        Dim k
        Dim AA
        Dim BB
        Dim CC
        Dim DD
        Dim a
        Dim b
        Dim c
        Dim d

        Const S11 = 7
        Const S12 = 12
        Const S13 = 17
        Const S14 = 22
        Const S21 = 5
        Const S22 = 9
        Const S23 = 14
        Const S24 = 20
        Const S31 = 4
        Const S32 = 11
        Const S33 = 16
        Const S34 = 23
        Const S41 = 6
        Const S42 = 10
        Const S43 = 15
        Const S44 = 21

        x = ConvertToWordArray(sMessage)

        a = &H67452301
        b = &HEFCDAB89
        c = &H98BADCFE
        d = &H10325476

        For k = 0 To UBound(x) Step 16
            AA = a
            BB = b
            CC = c
            DD = d

            FF a, b, c, d, x(k + 0), S11, &HD76AA478
            FF d, a, b, c, x(k + 1), S12, &HE8C7B756
            FF c, d, a, b, x(k + 2), S13, &H242070DB
            FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
            FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
            FF d, a, b, c, x(k + 5), S12, &H4787C62A
            FF c, d, a, b, x(k + 6), S13, &HA8304613
            FF b, c, d, a, x(k + 7), S14, &HFD469501
            FF a, b, c, d, x(k + 8), S11, &H698098D8
            FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
            FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
            FF b, c, d, a, x(k + 11), S14, &H895CD7BE
            FF a, b, c, d, x(k + 12), S11, &H6B901122
            FF d, a, b, c, x(k + 13), S12, &HFD987193
            FF c, d, a, b, x(k + 14), S13, &HA679438E
            FF b, c, d, a, x(k + 15), S14, &H49B40821

            GG a, b, c, d, x(k + 1), S21, &HF61E2562
            GG d, a, b, c, x(k + 6), S22, &HC040B340
            GG c, d, a, b, x(k + 11), S23, &H265E5A51
            GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
            GG a, b, c, d, x(k + 5), S21, &HD62F105D
            GG d, a, b, c, x(k + 10), S22, &H2441453
            GG c, d, a, b, x(k + 15), S23, &HD8A1E681
            GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
            GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
            GG d, a, b, c, x(k + 14), S22, &HC33707D6
            GG c, d, a, b, x(k + 3), S23, &HF4D50D87
            GG b, c, d, a, x(k + 8), S24, &H455A14ED
            GG a, b, c, d, x(k + 13), S21, &HA9E3E905
            GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
            GG c, d, a, b, x(k + 7), S23, &H676F02D9
            GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A

            HH a, b, c, d, x(k + 5), S31, &HFFFA3942
            HH d, a, b, c, x(k + 8), S32, &H8771F681
            HH c, d, a, b, x(k + 11), S33, &H6D9D6122
            HH b, c, d, a, x(k + 14), S34, &HFDE5380C
            HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
            HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
            HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
            HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
            HH a, b, c, d, x(k + 13), S31, &H289B7EC6
            HH d, a, b, c, x(k + 0), S32, &HEAA127FA
            HH c, d, a, b, x(k + 3), S33, &HD4EF3085
            HH b, c, d, a, x(k + 6), S34, &H4881D05
            HH a, b, c, d, x(k + 9), S31, &HD9D4D039
            HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
            HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
            HH b, c, d, a, x(k + 2), S34, &HC4AC5665

            II a, b, c, d, x(k + 0), S41, &HF4292244
            II d, a, b, c, x(k + 7), S42, &H432AFF97
            II c, d, a, b, x(k + 14), S43, &HAB9423A7
            II b, c, d, a, x(k + 5), S44, &HFC93A039
            II a, b, c, d, x(k + 12), S41, &H655B59C3
            II d, a, b, c, x(k + 3), S42, &H8F0CCC92
            II c, d, a, b, x(k + 10), S43, &HFFEFF47D
            II b, c, d, a, x(k + 1), S44, &H85845DD1
            II a, b, c, d, x(k + 8), S41, &H6FA87E4F
            II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
            II c, d, a, b, x(k + 6), S43, &HA3014314
            II b, c, d, a, x(k + 13), S44, &H4E0811A1
            II a, b, c, d, x(k + 4), S41, &HF7537E82
            II d, a, b, c, x(k + 11), S42, &HBD3AF235
            II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
            II b, c, d, a, x(k + 9), S44, &HEB86D391

            a = AddUnsigned(a, AA)
            b = AddUnsigned(b, BB)
            c = AddUnsigned(c, CC)
            d = AddUnsigned(d, DD)
        Next

        MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
    End Function

How to get the employees with their managers

(SELECT ename FROM EMP WHERE empno = mgr)

There are no records in EMP that meet this criteria.

You need to self-join to get this relation.

SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;

EDIT:

The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:

> select * from emp;

 empno | ename |    job    | deptno | mgr  
-------+-------+-----------+--------+------
  7839 | king  | president |     10 |     
  7698 | blake | manager   |     30 | 7839
(2 rows)

> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;

 employee | empno | manager | empno 
----------+-------+---------+-------
 king     |  7839 |         |      
 blake    |  7698 | king    |  7839
(2 rows)

The difference is that an outer join returns all the rows. An inner join will produce the following:

> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;

 ename | empno | manager | mgr  
-------+-------+---------+------
 blake |  7698 | king    | 7839
(1 row)

How to add one column into existing SQL Table

alter table table_name add field_name (size);

alter table arnicsc add place number(10);

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

parseInt with jQuery

var test = parseInt($("#testid").val());

How to take the first N items from a generator or list?

import itertools

top5 = itertools.islice(array, 5)

HTML input field hint

You'd need attach an onFocus event to the input field via Javascript:

<input type="text" onfocus="this.value=''" value="..." ... />

Printing to the console in Google Apps Script?

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

Yes, I wrote a little groovy script which does the trick You should add a 'Dynamic Choice Parameter' to your job and customize the following groovy script to your needs :

#!/usr/bin/groovy

def gitURL = "git repo url"
def command = "git ls-remote --heads --tags ${gitURL}"

def proc = command.execute()
proc.waitFor()              

if ( proc.exitValue() != 0 ) {
   println "Error, ${proc.err.text}"
   System.exit(-1)
}

def text = proc.in.text
# put your version string match
def match = /<REGEX>/
def tags = []

text.eachMatch(match) { tags.push(it[1]) }
tags.unique()
tags.sort( { a, b ->
         def a1 = a.tokenize('._-')
         def b1 = b.tokenize('._-')
         try {
            for (i in 1..<[a1.size(), b1.size()].min()) { 
                 if (a1[i].toInteger() != b1[i].toInteger()) return a1[i].toInteger() <=> b1[i].toInteger()
            }
            return 1
         } catch (e) {
            return -1;
         }
} )
tags.reverse()

I my case the version string was in the following format X.X.X.X and could have user branches in the format X.X.X-username ,etc... So I had to write my own sort function. This was my first groovy script so if there are better ways of doing thing I would like to know.

What causes a java.lang.StackOverflowError

Solution for Hibernate users when parsing datas:

I had this error because I was parsing a list of objects mapped on both sides @OneToMany and @ManyToOne to json using jackson which caused an infinite loop.

If you are in the same situation you can solve this by using @JsonManagedReference and @JsonBackReference annotations.

Definitions from API :

  • JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :

    Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property annotated with JsonBackReference. Linkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling

  • JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):

    Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

Example:

Owner.java:

@JsonManagedReference
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
Set<Car> cars;

Car.java:

@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
private Owner owner;

Another solution is to use @JsonIgnore which will just set null to the field.

Convert string to int if string is a number

Use IsNumeric. It returns true if it's a number or false otherwise.

Public Sub NumTest()
    On Error GoTo MyErrorHandler

    Dim myVar As Variant
    myVar = 11.2 'Or whatever

    Dim finalNumber As Integer
    If IsNumeric(myVar) Then
        finalNumber = CInt(myVar)
    Else
        finalNumber = 0
    End If

    Exit Sub

MyErrorHandler:
    MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _
        vbCrLf & "Description: " & Err.Description
End Sub

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

Converting String to "Character" array in Java

This method take String as a argument and return the Character Array

/**
 * @param sourceString
 *            :String as argument
 * @return CharcterArray
 */
public static Character[] toCharacterArray(String sourceString) {
    char[] charArrays = new char[sourceString.length()];
    charArrays = sourceString.toCharArray();
    Character[] characterArray = new Character[charArrays.length];
    for (int i = 0; i < charArrays.length; i++) {
        characterArray[i] = charArrays[i];
    }
    return characterArray;
}

Tuple unpacking in for loops

Take this code as an example:

elements = ['a', 'b', 'c', 'd', 'e']
index = 0

for element in elements:
  print element, index
  index += 1

You loop over the list and store an index variable as well. enumerate() does the same thing, but more concisely:

elements = ['a', 'b', 'c', 'd', 'e']

for index, element in enumerate(elements):
  print element, index

The index, element notation is required because enumerate returns a tuple ((1, 'a'), (2, 'b'), ...) that is unpacked into two different variables.

Using ffmpeg to encode a high quality video

Make sure the PNGs are fully opaque before creating the video

e.g. with imagemagick, give them a black background:

convert 0.png -background black -flatten +matte 0_opaque.png

From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency

How do I disable a jquery-ui draggable?

To enable/disable draggable in jQuery I used:

$("#draggable").draggable({ disabled: true });          

$("#draggable").draggable({ disabled: false });

@Calciphus answer didn't work for me with the opacity problem, so I used:

div.ui-state-disabled.ui-draggable-disabled {opacity: 1;}

Worked on mobile devices either.

Here is the code: http://jsfiddle.net/nn5aL/1/

Reducing MongoDB database file size

Mongodb 3.0 and higher has a new storage engine - WiredTiger. In my case switching engine reduced disk usage from 100 Gb to 25Gb.

How to check not in array element

I prefer this

if(in_array($id,$user_access_arr) == false)

respective

if (in_array(search_value, array) == false) 
// value is not in array 

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

Get bitcoin historical data

Actually, you CAN get the whole Bitcoin trades history from Bitcoincharts in CSV format here : http://api.bitcoincharts.com/v1/csv/

it is updated twice a day for active exchanges, and there is a few dead exchanges, too.

EDIT: Since there are no column headers in the CSVs, here's what they are : column 1) the trade's timestamp, column 2) the price, column 3) the volume of the trade

Bootstrap: add margin/padding space between columns

For those looking to control the space between a dynamic number of columns, try:

<div class="row no-gutters">
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <!-- etc. -->
</div>

CSS:

.col:not(:last-child) .inner {
  margin: 2px; // Or whatever you want your spacing to be
}

Pass C# ASP.NET array to Javascript array

Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.

var page = HttpContext.Current.CurrentHandler as Page;

_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
         ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);

This code creates an array on the client side

var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
             ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);

See the following article

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerarraydeclaration?view=netframework-4.8

This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.

AngularJS - Trigger when radio button is selected

For dynamic values!

<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
    <label class="control-label">
        <input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />              
        <span ng-bind="v"></span>
    </label>
</div>

in controller

$scope.changeTipoAcesso = function(value) {
    console.log(value);
};

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

I was same problem, but for me the problem was ng build command. I was doing "ng build --prod" i have corrected it to "ng build --prod --base-href /applicationname/". and this solved my problem.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

I found out that the naming of my css files was in conflict with the proxy filters

www.dating.com (which is not my site) was blocked and my css and js files were called dating.css and dating.js. The filter was blocking this. Maybe that is the case with some of you, working on corporates systems.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Draggable div without jQuery UI

$(document).ready(function() {
    var $startAt = null;

    $(document.body).live("mousemove", function(e) {
        if ($startAt) {
            $("#someDiv").offset({
                top: e.pageY,
                left: $("#someDiv").position().left-$startAt+e.pageX
            });
            $startAt = e.pageX; 
        }
    });

    $("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
    $(document.body).live("mouseup", function (e) {$startAt = null;});
});

Share cookie between subdomain and domain

I'm not sure @cmbuckley answer is showing the full picture. What I read is:

Unless the cookie's attributes indicate otherwise, the cookie is returned only to the origin server (and not, for example, to any subdomains), and it expires at the end of the current session (as defined by the user agent). User agents ignore unrecognized cookie.

RFC 6265

Also

8.6.  Weak Integrity

   Cookies do not provide integrity guarantees for sibling domains (and
   their subdomains).  For example, consider foo.example.com and
   bar.example.com.  The foo.example.com server can set a cookie with a
   Domain attribute of "example.com" (possibly overwriting an existing
   "example.com" cookie set by bar.example.com), and the user agent will
   include that cookie in HTTP requests to bar.example.com.  In the
   worst case, bar.example.com will be unable to distinguish this cookie
   from a cookie it set itself.  The foo.example.com server might be
   able to leverage this ability to mount an attack against
   bar.example.com.

To me that means you can protect cookies from being read by subdomain/domain but cannot prevent writing cookies to the other domains. So somebody may rewrite your site cookies by controlling another subdomain visited by the same browser. Which might not be a big concern.

Awesome cookies test site provided by @cmbuckley /for those that missed it in his answer like me; worth scrolling up and upvoting/:

Nested JSON: How to add (push) new items to an object?

If your JSON is without key you can do it like this:

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

So, try this:

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

Then:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

Boolean vs boolean in Java

You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

  1. With primitives you guarantee that you will not pass null values.
    You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):

    public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans