Programs & Examples On #Modern runtime

Reset CSS display property to default value

If using javascript is allowed, you can set the display property to an empty string. This will cause it to use the default for that particular element.

var element = document.querySelector('span.selector');

// Set display to empty string to use default for that element = '';

Here is a link to a jsbin.

This is nice because you don't have to worry about the different types of display to revert to (block, inline, inline-block, table-cell, etc).

But, it requires javascript, so if you are looking for a css-only solution, then this is not the solution for you.

Note: This overrides inline styles, but not styles set in css

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

We can use the below its very simple.


Change WPF window background image in C# code

I have been trying all the answers here with no success. Here is the simplest way to do it with ms-appx

        ImageBrush myBrush = new ImageBrush();
        Image image = new Image();
        image.Source = new BitmapImage(new Uri(@"ms-appx:///Assets/background.jpg"));
        myBrush.ImageSource = image.Source;
        TheGrid.Background = myBrush;

Assets folder is in the first level of my project, so make sure to change the path as convenient.

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

First must be Alphabet and then dot not allowed in target string. below is code.

        string input = "A_aaA";

        // B
        // The regular expression we use to match
        Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.

        // C
        // Match the input and write results
        Match match = r1.Match(input);
        if (match.Success)
            Console.WriteLine("Valid: {0}", match.Value);

            Console.WriteLine("Not Match");


ExecuteNonQuery doesn't return results

if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement.

How to Set Count On

What's the quickest way to multiply multiple cells by another number?

Put the number you want to multiply by in a cell that is not in your range. Select the cell and "Copy" it to the clipboard. Next, select the Range A1:D5, and from the menu choose Edit|Paste Special. A dialog box will appear. In the "Operation" area, select "Multiply" and click "OK".

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))

How to update and delete a cookie?

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
    return null;

function eraseCookie(name) {

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

How to reset Android Studio

Linux Android Studio 0.8.6:

rm -R ~/.AndroidStudioBeta/config/

Linux Android Studio 1.0.0:

rm -R ~/.AndroidStudio/config/

How to remove elements from a generic list while iterating over it?

Copy the list you are iterating. Then remove from the copy and interate the original. Going backwards is confusing and doesn't work well when looping in parallel.

var ids = new List<int> { 1, 2, 3, 4 };
var iterableIds = ids.ToList();

Parallel.ForEach(iterableIds, id =>

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Adding a file, and then deleting it is the kind of operation that's considered an error - and so SVN is telling you. You told it to expect some file data and then don't supply it when you commit, the red lights flash and the sirens go off!

The answer is to undo your add, alternatively commit the file and then use 'svn rm' to remove it from the filesystem and the repo.

Change the color of a bullet in a html list?

<ul style="color: red;">
  • One
  • Two
  • Three
  • DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

    Use HH for 24 hour hours format:

    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

    Or the tt format specifier for the AM/PM part:

    DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

    Take a look at the custom Date and Time format strings documentation.

    How can I initialize a MySQL database with schema in a Docker container?

    I had this same issue where I wanted to initialize my MySQL Docker instance's schema, but I ran into difficulty getting this working after doing some Googling and following others' examples. Here's how I solved it.

    1) Dump your MySQL schema to a file.

    mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_name> > schema.sql

    2) Use the ADD command to add your schema file to the /docker-entrypoint-initdb.d directory in the Docker container. The file will run any files in this directory ending with ".sql" against the MySQL database.


    FROM mysql:5.7.15
    ENV MYSQL_DATABASE=<schema_name> \
    ADD schema.sql /docker-entrypoint-initdb.d
    EXPOSE 3306

    3) Start up the Docker MySQL instance.

    docker-compose build
    docker-compose up

    Thanks to Setting up MySQL and importing dump within Dockerfile for clueing me in on the and the fact that it runs both SQL and shell scripts!

    How do you display a Toast from a background thread on Android?

    1. Get UI Thread Handler instance and use handler.sendMessage();
    2. Call post() method;
    3. runOnUiThread()

    Does a finally block always get executed in Java?

    In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:

    public static int getMonthsInYear() {
        try {
            return 10;
        finally {
            return 12;

    Similarly, the following method does not throw an exception:

    public static int getMonthsInYear() {
        try {
            throw new RuntimeException();
        finally {
            return 12;

    While the following method does throw it:

    public static int getMonthsInYear() {
        try {
            return 12;          
        finally {
            throw new RuntimeException();

    TSQL - Cast string to integer or return default value

    Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.

    Casting to a money or float first handles both the currency and scientific issues:

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
    DROP FUNCTION [dbo].[TryConvertInt]
    CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
    RETURNS bigint
        DECLARE @IntValue bigint;
        IF (ISNUMERIC(@Value) = 1)
            IF (@Value like '%e%')
                SET @IntValue = CAST(Cast(@Value as float) as bigint);
                SET @IntValue = CAST(CAST(@Value as money) as bigint);
            SET @IntValue = NULL;
        RETURN @IntValue;

    The function will fail if the number is bigger than a bigint.

    If you want to return a different default value, leave this function so it is generic and replace the null afterwards:

    SELECT IsNull(dbo.TryConvertInt('nan') , 1000);

    Is it possible to specify proxy credentials in your web.config?

    While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:

        <defaultProxy useDefaultCredentials="true">
          <proxy proxyaddress="proxyAddress" usesystemdefault="True"/>

    The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.

    Are there inline functions in java?

    so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:

        assert false : new<Void,String>(){
            @Override public String apply(Void input) {
                //your complex code go here
                return "weird message";

    yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!

    Update int column in table with unique incrementing values

    Try something like this:

    with toupdate as (
        select p.*,
               (coalesce(max(interfaceid) over (), 0) +
                row_number() over (order by (select NULL))
               ) as newInterfaceId
        from prices
    update p
        set interfaceId = newInterfaceId
        where interfaceId is NULL

    This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

    with toupdate as (
        select p.*,
               (coalesce(max(interfaceid) over (), 0) +
                row_number() over (partition by interfaceId order by (select NULL))
               ) as newInterfaceId
        from prices
    update p
        set interfaceId = newInterfaceId
        where interfaceId is NULL

    Why Response.Redirect causes System.Threading.ThreadAbortException?

    This is just how Response.Redirect(url, true) works. It throws the ThreadAbortException to abort the thread. Just ignore that exception. (I presume it is some global error handler/logger where you see it?)

    An interesting related discussion Is Response.End() Considered Harmful?.

    Subscript out of range error in this Excel VBA script

    Private Sub CommandButton1_Click()
        Dim Data As Object, Employee As Object
        Application.ScreenUpdating = False
        Set Data = ThisWorkbook.Sheets("Data")
        Set Employee = ThisWorkbook.Sheets("Employee Names")
        Data.Range("AK1").Value = "Lookup"
        Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"
        Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"
        Application.DisplayAlerts = False
        Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
        Data.AutoFilterMode = False
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
        Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"
        Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")
        Dr.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
        Data.AutoFilterMode = False
        'DrfeeRequested.AutoFilterMode = False
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
        Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")
        Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
        Data.AutoFilterMode = False
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
        Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")
        Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
        Data.AutoFilterMode = False
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"
        Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")
        Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
        Data.AutoFilterMode = False
        TodayDT = Format(Now())
        Weekdy = Weekday(Now())
        If Weekdy = 2 Then
           LastTwoDays = Now() - Weekday(Now(), 3)
        ElseIf Weekdy = 3 Then
           LastTwoDays = Now() - Weekday(Now(), 3)
        ElseIf Weekdy = 4 Then
           LastTwoDays = Now() - Weekday(Now(), 3)
        ElseIf Weekdy = 5 Then
           LastTwoDays = Now() - Weekday(Now(), 3)
        ElseIf Weekdy = 6 Then
           LastTwoDays = Now() - Weekday(Now(), 3)
           MsgBox "Today Satuarday OR Sunday Data is not Available"
        End If
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"
        Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")
        Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
        Data.AutoFilterMode = False
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
        'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"
        Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"
        Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")
        Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
       End Sub
     Private Sub CommandButton2_Click()
        Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear
        MsgBox "Please paste new data in data sheet"
    End Sub

    How do I delete NuGet packages that are not referenced by any project in my solution?

    If you want to use Visual Studio option, please see How to remove Nuget Packages from Existing Visual Studio solution:

    Step 1:

    In Visual Studio, Go to Tools/NuGet Package Manager/Manage NuGet Packages for Solution…

    Step 2:

    UnCheck your project(s) from Current solution

    Step 3:

    Unselect project(s) and press OK

    Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

    this worked for me:

    ProxyRequests     Off
    ProxyPreserveHost On
    RewriteEngine On
    <Proxy http://localhost:8123>
    Order deny,allow
    Allow from all
    ProxyPass         /node  http://localhost:8123  
    ProxyPassReverse  /node  http://localhost:8123

    Parameter in like clause JPQL

    There is nice like() method in JPA criteria API. Try to use that, hope it will help.

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = cb.createQuery(Employees.class);
    Root<Employees> rootOfQuery = criteriaQuery.from(Employees.class);"firstName"), "H%"));

    Incorrect syntax near ''

    I was using ADO.NET and was using SQL Command as:

     string query =
    "SELECT * " +
    "FROM table_name" +
    "Where id=@id";

    the thing was i missed a whitespace at the end of "FROM table_name"+ So basically it said

    string query = "SELECT * FROM table_nameWHERE id=@id";

    and this was causing the error.

    Hope it helps

    Java verify void method calls n times with Mockito

    The necessary method is Mockito#verify:

    public static <T> T verify(T mock,
                               VerificationMode mode)

    mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

    verify(mock, times(5)).someMethod("was called five times");
    verify(mock, never()).someMethod("was never called");
    verify(mock, atLeastOnce()).someMethod("was called at least once");
    verify(mock, atLeast(2)).someMethod("was called at least twice");
    verify(mock, atMost(3)).someMethod("was called at most 3 times");
    verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
    verify(mock, only()).someMethod("no other method has been called on the mock");

    You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

    import static org.mockito.Mockito.atLeast;
    import static org.mockito.Mockito.atLeastOnce;
    import static org.mockito.Mockito.atMost;
    import static org.mockito.Mockito.never;
    import static org.mockito.Mockito.only;
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;

    So in your case the correct syntax will be:

    Mockito.verify(mock, times(4)).send()

    This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.

    If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

    verify(mock).someMethod("was called once");

    would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.

    It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

    verify(mock, atLeast(4)).someMethod("was called at least four times ...");
    verify(mock, atMost(6)).someMethod("... and not more than six times");

    instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

    Tainted canvases may not be exported

    In the img tag set crossorigin to Anonymous.

    <img crossorigin="anonymous"></img>

    Getting the text from a drop-down box

    Attaches a change event to the select that gets the text for each selected option and writes them in the div.

    You can use jQuery it very face and successful and easy to use

    <select name="sweets" multiple="multiple">
      <option selected="selected">Caramel</option>
    $("select").change(function () {
      var str = "";
      $("select option:selected").each(function() {
        str += $( this ).text() + " ";
      $( "div" ).text( str );

    How to Replace Multiple Characters in SQL?

    I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.

    Laravel Eloquent LEFT JOIN WHERE NULL

    You can also specify the columns in a select like so:

    $c = Customer::select('*', DB::raw(' AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
    ->leftJoin('orders', function($join) {
      $join->on('', '=', 'orders.customer_id') 

    How to change facebook login button with my custom image

    It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.

    From facebook:

    size - Different sized buttons: small, medium, large, xlarge - the default is medium.

    Set the login iframe opacity to 0 and show a background image in the parent div

    .fb_iframe_widget iframe {
        opacity: 0;
    .fb_iframe_widget {
      background-image: url(another-button.png);
      background-repeat: no-repeat; 

    If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.

    How to show a GUI message box from a bash script in linux?

    I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.

    Change bundle identifier in Xcode when submitting my first app in IOS

    View this picture to see how you can change the bundle identifier


    1. Select your project form the leftmost project navigator
    2. Under the General Tab, there is a section called Targets inside where you will see the name of your project. Click on the name.
    3. Then you will be able to see the bundle identifier which you can change as below:

    As you can see in the picture, the name of my App is PracticeApp. And my bundle identifier is: com.hello500.PracticeApp

    In this case, You can change hello500 to change the bundle identifier of the app.

    Setting a windows batch file variable to the day of the week

    Locale-dependent version: In some environments, the following will extract the day name from the date:

    set dayname=%date:~0,3%

    It assumes that the day name is the first part of %date%. Depending on the machine settings, though, the substring part (~0,3) would need to change.

    A statement such as this would dump to a file with a three character day name:

    set logfile=%date:~0,3%.log
    echo some stuff > %logfile%

    Locale-independent version: If you need it less dependent on the current machine's day format, another way of doing it would be to write a tiny application that prints the day of the week. Then use the output of that program from the batch file. For example, the following C application prints dayN where N=0..6.

    #include <stdio.h>
    #include <time.h>
    int main( int argc, char* argv[] )
       time_t curtime;
       struct tm * tmval;
       time( &curtime );
       tmval = localtime( &curtime );
       // print dayN.  Or use a switch statement and print
       // the actual day name if you want
       printf( "day%d", tmval->tm_wday );

    If the above were compiled and linked as myday.exe, then you could use it from a batch file like this:

    for /f %%d in ('myday.exe') do set logfile=%%d.log
    echo some stuff > %logfile%

    Detecting an undefined object property

    In JavaScript, there are truthy and falsy expressions. If you want to check if the property is undefined or not, there is a straight way of using an if condition as given,

    1. Using truthy/falsy concept.
        console.log('someProp is falsy')

    However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.

    1. Using === undefined check in if condition
    if(ob.someProp === undefined){
        console.log('someProp is undefined')
    1. Using typeof

    typeof acts as a combined check for the value undefined and for whether a variable exists.

    if(typeof ob.someProp === 'undefined'){
        console.log('someProp is undefined')
    1. Using hasOwnProperty method

    The JavaScript object has built in the hasOwnProperty function in the object prototype.

        console.log('someProp is undefined')

    Not going in deep, but the 1st way looks shortened and good to me. Here are the details on truthy/falsy values in JavaScript and undefined is the falsy value listed in there. So the if condition behaves normally without any glitch. Apart from the undefined, values NaN, false (Obviously), '' (empty string) and number 0 are also the falsy values.

    Warning: Make sure the property value does not contain any falsy value, otherwise the if condition will return false. For such a case, you can use the hasOwnProperty method

    Spring Boot - Handle to Hibernate SessionFactory

    If it's really required to access SessionFactory through @Autowire, I'd rather configure another EntityManagerFactory and then use it to configure the SessionFactory bean, like following:

    public class SessionFactoryConfig {
    DataSource dataSource;
    JpaVendorAdapter jpaVendorAdapter;
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        return emf.getObject();
    public SessionFactory setSessionFactory(EntityManagerFactory entityManagerFactory) {
        return entityManagerFactory.unwrap(SessionFactory.class);
    } }

    where does MySQL store database files?

    For WampServer, click on its tray icon and then in the popup cascading menu select

    MySQL | MySQL settings | datadir

    MySQL Data Directory

    Indent List in HTML and CSS

    li {
      padding-left: 30px;
    <p>Some text to show left edge of container.<p>
      <li>List item</li>
    _x000D_ The above will add 30px of space between the bullet or number and your text.

    li {
      margin-left: 30px;
    <p>Some text to show left edge of container.<p>
      <li>List item</li>
    _x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

    How to get a dependency tree for an artifact?

    1) Use maven dependency plugin

    Create a simple project with pom.xml only. Add your dependency and run:

    mvn dependency:tree

    Unfortunately dependency mojo must use pom.xml or you get following error:

    Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.

    2) Find pom.xml of your artifact in maven central repository

    Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.

    Go to and enter your groupId and artifactId.

    Or you can go to and navigate first using plugins groupId, later using artifactId and finally using its version.

    For example see org.springframework:spring-core

    3) Use maven dependency plugin against your artifact

    Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.

    Why does background-color have no effect on this DIV?

    Floats don't have a height so the containing div has a height of zero.

    <div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
    <div style="float:left">hello</div>
    <div style="float:right">world</div>

    overflow:hidden clears the float for most browsers.

    zoom:1 clears the float for IE.

    How to store a list in a column of a database table

    you can store it as text that looks like a list and create a function that can return its data as an actual list. example:


    |  word  | letters    |
    |   me   | '[m, e]'   |
    |  you   |'[y, o, u]' |  note that the letters column is of type 'TEXT'
    |  for   |'[f, o, r]' |
    |___in___|_'[i, n]'___|

    And the list compiler function (written in python, but it should be easily translatable to most other programming languages). TEXT represents the text loaded from the sql table. returns list of strings from string containing list. if you want it to return ints instead of strings, make mode equal to 'int'. Likewise with 'string', 'bool', or 'float'.

    def string_to_list(string, mode):
        items = []
        item = ""
        itemExpected = True
        for char in string[1:]:
            if itemExpected and char not in [']', ',', '[']:
                item += char
            elif char in [',', '[', ']']:
                itemExpected = True
                item = ""
        newItems = []
        if mode == "int":
            for i in items:
        elif mode == "float":
            for i in items:
        elif mode == "boolean":
            for i in items:
                if i in ["true", "True"]:
                elif i in ["false", "False"]:
        elif mode == "string":
            return items
            raise Exception("the 'mode'/second parameter of string_to_list() must be one of: 'int', 'string', 'bool', or 'float'")
        return newItems

    Also here is a list-to-string function in case you need it.

    def list_to_string(lst):
        string = "["
        for i in lst:
            string += str(i) + ","
        if string[-1] == ',':
            string = string[:-1] + "]"
            string += "]"
        return string

    Set Culture in an ASP.Net MVC app

    I know this is an old question, but if you really would like to have this working with your ModelBinder (in respect to DefaultModelBinder.ResourceClassKey = "MyResource"; as well as the resources indicated in the data annotations of the viewmodel classes), the controller or even an ActionFilter is too late to set the culture.

    The culture could be set in Application_AcquireRequestState, for example:

    protected void Application_AcquireRequestState(object sender, EventArgs e)
            // For example a cookie, but better extract it from the url
            string culture = HttpContext.Current.Request.Cookies["culture"].Value;
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);


    Actually there is a better way using a custom routehandler which sets the culture according to the url, perfectly described by Alex Adamyan on his blog.

    All there is to do is to override the GetHttpHandler method and set the culture there.

    public class MultiCultureMvcRouteHandler : MvcRouteHandler
        protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
            // get culture from route data
            var culture = requestContext.RouteData.Values["culture"].ToString();
            var ci = new CultureInfo(culture);
            Thread.CurrentThread.CurrentUICulture = ci;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
            return base.GetHttpHandler(requestContext);

    vertical align middle in <div>

     div {_x000D_
        text-align: center;_x000D_
        padding: 2px;_x000D_
        border: 1px solid #000;_x000D_
        background-color: green;_x000D_
    .text-align-center {_x000D_
        display: flex;_x000D_
        align-items: center;_x000D_
        justify-content: center;_x000D_
    <div class="text-align-center"> Align center</div>

    How to make URL/Phone-clickable UILabel?

    extension UITapGestureRecognizer {
        func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
            let layoutManager = NSLayoutManager()
            let textContainer = NSTextContainer(size:
            let textStorage = NSTextStorage(attributedString: label.attributedText!)
            // Configure layoutManager and textStorage
            // Configure textContainer
            textContainer.lineFragmentPadding = 0.0
            textContainer.lineBreakMode = label.lineBreakMode
            textContainer.maximumNumberOfLines = label.numberOfLines
            textContainer.size = label.bounds.size
            // main code
            let locationOfTouchInLabel = self.location(in: label)
            let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
            let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1)
            let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer)
            let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width
            if locationOfTouchInLabel.x > deltaOffsetCharacter {
                return false
            } else {
                return NSLocationInRange(indexOfCharacter, targetRange)

    Count with IF condition in MySQL query

    This should work:

    count(if( = 'approved',, NULL))

    count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.

    How do I check whether a file exists without exceptions?

    If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

    If you're not planning to open the file immediately, you can use os.path.isfile

    Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

    import os.path

    if you need to be sure it's a file.

    Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

    from pathlib import Path
    my_file = Path("/path/to/file")
    if my_file.is_file():
        # file exists

    To check a directory, do:

    if my_file.is_dir():
        # directory exists

    To check whether a Path object exists independently of whether is it a file or directory, use exists():

    if my_file.exists():
        # path exists

    You can also use resolve(strict=True) in a try block:

        my_abs_path = my_file.resolve(strict=True)
    except FileNotFoundError:
        # doesn't exist
        # exists

    Define static method in source-file with declaration in header-file in C++

    Static member functions must refer to static variables of that class. So in your case,

    static void CP_StringToPString( std::string& inString, unsigned char *outString);

    Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

    The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

    You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

    How to test multiple variables against a value?

    The direct way to write x or y or z == 0 is

    if any(map((lambda value: value == 0), (x,y,z))):
        pass # write your logic.

    But I dont think, you like it. :) And this way is ugly.

    The other way (a better) is:

    0 in (x, y, z)

    BTW lots of ifs could be written as something like this

    my_cases = {
        0: Mylist.append("c"),
        1: Mylist.append("d")
        # ..
    for key in my_cases:
        if key in (x,y,z):

    Write a number with two decimal places SQL Server

    This will allow total 10 digits with 2 values after the decimal. It means that it can accomodate the value value before decimal upto 8 digits and 2 after decimal.

    To validate, put the value in the following query.

    DECLARE vtest  number(10,2);
    SELECT 10.008 INTO vtest FROM dual;

    BeanFactory not initialized or already closed - call 'refresh' before

    In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.

    How to retrieve field names from temporary table (SQL Server 2008)

    The temporary tables are defined in "tempdb", and the table names are "mangled".

    This query should do the trick:

    select c.*
    from tempdb.sys.columns c
    inner join tempdb.sys.tables t ON c.object_id = t.object_id
    where like '#MyTempTable%'


    css to make bootstrap navbar transparent

    Simply add this to your css :-

    .navbar-inner {

    How to set selected item of Spinner by value, not by position?

    Here is how to do it if you are using a SimpleCursorAdapter (where columnName is the name of the db column that you used to populate your spinner):

    private int getIndex(Spinner spinner, String columnName, String searchString) {
        //Log.d(LOG_TAG, "getIndex(" + searchString + ")");
        if (searchString == null || spinner.getCount() == 0) {
            return -1; // Not found
        else {
            Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
            int initialCursorPos = cursor.getPosition(); //  Remember for later
            int index = -1; // Not found
            for (int i = 0; i < spinner.getCount(); i++) {
                String itemText = cursor.getString(cursor.getColumnIndex(columnName));
                if (itemText.equals(searchString)) {
                    index = i; // Found!
            cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.
            return index;

    Also (a refinement of Akhil's answer) this is the corresponding way to do it if you are filling your Spinner from an array:

    private int getIndex(Spinner spinner, String searchString) {
        if (searchString == null || spinner.getCount() == 0) {
            return -1; // Not found
        else {
            for (int i = 0; i < spinner.getCount(); i++) {
                if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
                    return i; // Found!
            return -1; // Not found

    Getting permission denied (public key) on gitlab

    I was facing this issue because of ssh-agent conflicts on Windows-10. If you are using Windows-10 as well then please go through my detailed solution to this here

    If you are not on windows-10 then please check if:

    1. your ssh-agent is running
    2. correct private key is added to your ssh-agent
    3. correct public key is added to your github account (You are able to clone, so this step should be fine)

    C# Parsing JSON array of objects

    Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future

     JArray array = JArray.Parse(jsonString);
     foreach (JObject obj in array.Children<JObject>())
         foreach (JProperty singleProp in obj.Properties())
             string name = singleProp.Name;
             string value = singleProp.Value.ToString();
             //Do something with name and value
             //System.Windows.MessageBox.Show("name is "+name+" and value is "+value);

    This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;

    Is it not possible to define multiple constructors in Python?

    Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

    def __init__(self, city="Berlin"): = city

    Passing multiple argument through CommandArgument of Button in

    You can pass semicolon separated values as command argument and then split the string and use it.

    <asp:TemplateField ShowHeader="false">
           <asp:LinkButton ID="lnkCustomize" Text="Customize"  CommandName="Customize"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 

    at server side

    protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
          string[] arg = new string[2];
          arg = e.CommandArgument.ToString().Split(';');
          Session["IdTemplate"] = arg[0];
          Session["IdEntity"] = arg[1];

    Hope it helps!!!!

    Notepad++ incrementally replace

    Since there are limited real answers I'll share this workaround. For really simple cases like your example you do it backwards...

    From this


    Replace \r\n with " />\r\n<row id=" and you'll get 90% of the way there

    1" />
    <row id="2" />
    <row id="3" />
    <row id="4" />
    <row id="5

    Or is a similar fashion you can hack about data with excel/spreadsheet. Just split your original data into columns and manipulate values as you require.

    |   <row id="   |   1   |   " />    |
    |   <row id="   |   1   |   " />    |
    |   <row id="   |   1   |   " />    |
    |   <row id="   |   1   |   " />    |
    |   <row id="   |   1   |   " />    |

    Obvious stuff but it may help someone doing the odd one-off hack job to save a few key strokes.

    How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

    Taking DWins example.

    What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".


    clab = 1.5
    cmain = 2
    caxis = 1.2
    plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
               col.lab="red", cex.lab=clab,    
               col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis) 

    You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:

    which you then call with setwd("") source("plotcolours.r")

    in a file say called plotcolours.r you then store all the e.g. colour or size variables

    clab = 1.5
    cmain = 2
    caxis = 1.2 

    for colours could use


    as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.


    How to remove focus without setting focus to another control?

    I tried to disable and enable focusability for view and it worked for me (focus was reset):


    Using a PHP variable in a text input value = statement

    From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:

    <?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>

    Access files stored on Amazon S3 through web browser

    You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").

    Your policy will look something like the following. You can use the S3 console at to upload it.

          "Principal": {
                "AWS": "*"

    If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.

    How to get the part of a file after the first line that matches a regular expression?

    As a simple approximation you could use

    grep -A100000 TERMINATE file

    which greps for TERMINATE and outputs up to 100000 lines following that line.

    From man page

    -A NUM, --after-context=NUM

    Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.

    Get Android shared preferences value in activity/normal class

    This is the procedure that seems simplest to me:

    SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
    SharedPreferences.Editor e = sp.edit();
        if (sp.getString("sharedString", null).equals("true")
                || sp.getString("sharedString", null) == null) {
            e.putString("sharedString", "false").commit();
            // Do something
        } else {
            // Do something else

    Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

    I have experienced that a drop-down menu, referring to a control range (for example after copying sheets from one workbook to another), will keep that cell reference after copying the worksheet, and keeps a data connection which is invisible in "Connections". I found this in the "Search" menu in the ribbon, where an arrow can be selected to mark objects. Underneath the arrow is a menu selection to see all the objects listed in a panel. Then you can delete those unwanted objects and the data source/connection is gone...

    How to launch an Activity from another Application in Android

    Here is my example of launching bar/QR code scanner from my app if someone finds it useful

    Intent intent = new Intent("");
        startActivityForResult(intent, SCAN_REQUEST_CODE);
    catch (ActivityNotFoundException e) 
        //implement prompt dialog asking user to download the package
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
                new DialogInterface.OnClickListener() 
                    public void onClick(DialogInterface dialogInterface, int i) 
                        Uri uri = Uri.parse("market://search?");
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        catch (ActivityNotFoundException e)
                            Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
                new DialogInterface.OnClickListener() 
                    public void onClick(DialogInterface dialog, int i) 

    Javascript replace all "%20" with a space

    Check this out: How to replace all occurrences of a string in JavaScript?

    Short answer:

    str.replace(/%20/g, " ");

    EDIT: In this case you could also do the following:


    Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

    I think the solution is to combine techniques from video encoding, namely the discrete cosine transformation. In digital video, rather recording the changing the brightness or colour of video as regular values such as 110 112 115 116, each is subtracted from the last (similar to run length encoding). 110 112 115 116 becomes 110 2 3 1. The values, 2 3 1 require less bits than the originals.

    So lets say we create a list of the input values as they arrive on the socket. We are storing in each element, not the value, but the offset of the one before it. We sort as we go, so the offsets are only going to be positive. But the offset could be 8 decimal digits wide which this fits in 3 bytes. Each element can't be 3 bytes, so we need to pack these. We could use the top bit of each byte as a "continue bit", indicating that the next byte is part of the number and the lower 7 bits of each byte need to be combined. zero is valid for duplicates.

    As the list fills up, the numbers should be get closer together, meaning on average only 1 byte is used to determine the distance to the next value. 7 bits of value and 1 bit of offset if convenient, but there may be a sweet spot that requires less than 8 bits for a "continue" value.

    Anyway, I did some experiment. I use a random number generator and I can fit a million sorted 8 digit decimal numbers into about 1279000 bytes. The average space between each number is consistently 99...

    public class Test {
        public static void main(String[] args) throws IOException {
            // 1 million values
            int[] values = new int[1000000];
            // create random values up to 8 digits lrong
            Random random = new Random();
            for (int x=0;x<values.length;x++) {
                values[x] = random.nextInt(100000000);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int av = 0;    
            writeCompact(baos, values[0]);     // first value
            for (int x=1;x<values.length;x++) {
                int v = values[x] - values[x-1];  // difference
                av += v;
                System.out.println(values[x] + " diff " + v);
                writeCompact(baos, v);
            System.out.println("Average offset " + (av/values.length));
            System.out.println("Fits in " + baos.toByteArray().length);
        public static void writeCompact(OutputStream os, long value) throws IOException {
            do {
                int b = (int) value & 0x7f;
                value = (value & 0x7fffffffffffffffl) >> 7;
                os.write(value == 0 ? b : (b | 0x80));
            } while (value != 0);

    Build fat static library (device + simulator) using Xcode and SDK 4+


    Easy copy/paste of latest version (but install instructions may change - see below!)

    Karl's library takes much more effort to setup, but much nicer long-term solution (it converts your library into a Framework).

    Use this, then tweak it to add support for Archive builds - c.f. @Frederik's comment below on the changes he's using to make this work nicely with Archive mode.

    RECENT CHANGES: 1. Added support for iOS 10.x (while maintaining support for older platforms)

    1. Info on how to use this script with a project-embedded-in-another-project (although I highly recommend NOT doing that, ever - Apple has a couple of show-stopper bugs in Xcode if you embed projects inside each other, from Xcode 3.x through to Xcode 4.6.x)

    2. Bonus script to let you auto-include Bundles (i.e. include PNG files, PLIST files etc from your library!) - see below (scroll to bottom)

    3. now supports iPhone5 (using Apple's workaround to the bugs in lipo). NOTE: the install instructions have changed (I can probably simplify this by changing the script in future, but don't want to risk it now)

    4. "copy headers" section now respects the build setting for the location of the public headers (courtesy of Frederik Wallner)

    5. Added explicit setting of SYMROOT (maybe need OBJROOT to be set too?), thanks to Doug Dickinson

    SCRIPT (this is what you have to copy/paste)

    For usage / install instructions, see below

    # c.f.
    # Version 2.82
    # Latest Change:
    # - MORE tweaks to get the iOS 10+ and 9- working
    # - Support iOS 10+
    # - Corrected typo for iOS 1-10+ (thanks @stuikomma)
    # Purpose:
    #   Automatically create a Universal static library for iPhone + iPad + iPhone Simulator from within XCode
    # Author: Adam Martin -
    # Based on: original script from Eonil (main changes: Eonil's script WILL NOT WORK in Xcode GUI - it WILL CRASH YOUR COMPUTER)
    set -e
    set -o pipefail
    #################[ Tests: helps workaround any future bugs in Xcode ]########
    if [ $DEBUG_THIS_SCRIPT = "true" ]
    echo "########### TESTS #############"
    echo "Use the following variables when debugging this script; note that they may change on recursions"
    echo "BUILD_DIR = $BUILD_DIR"
    #####################[ part 1 ]##################
    # First, work out the BASESDK version number (NB: Apple ought to report this, but they hide it)
    #    (incidental: searching for substrings in sh is a nightmare! Sob)
    SDK_VERSION=$(echo ${SDK_NAME} | grep -o '\d\{1,2\}\.\d\{1,2\}$')
    # Next, work out if we're in SIM or DEVICE
    if [ ${PLATFORM_NAME} = "iphonesimulator" ]
    echo "XCode has selected SDK: ${PLATFORM_NAME} with version: ${SDK_VERSION} (although back-targetting: ${IPHONEOS_DEPLOYMENT_TARGET})"
    echo "...therefore, OTHER_SDK_TO_BUILD = ${OTHER_SDK_TO_BUILD}"
    #####################[ end of part 1 ]##################
    #####################[ part 2 ]##################
    # IF this is the original invocation, invoke WHATEVER other builds are required
    # Xcode is already building ONE target...
    # ...but this is a LIBRARY, so Apple is wrong to set it to build just one.
    # ...we need to build ALL targets
    # ...we MUST NOT re-build the target that is ALREADY being built: Xcode WILL CRASH YOUR COMPUTER if you try this (infinite recursion!)
    # So: build ONLY the missing platforms/configurations.
    if [ "true" == ${ALREADYINVOKED:-false} ]
    echo "RECURSION: I am NOT the root invocation, so I'm NOT going to recurse"
    # Prevent infinite recursion (Xcode sucks)
    export ALREADYINVOKED="true"
    echo "RECURSION: I am the root ... recursing all missing build targets NOW..."
    echo "RECURSION: ...about to invoke: xcodebuild -configuration \"${CONFIGURATION}\" -project \"${PROJECT_NAME}.xcodeproj\" -target \"${TARGET_NAME}\" -sdk \"${OTHER_SDK_TO_BUILD}\" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO" BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" SYMROOT=\"${SYMROOT}\"
    #Merge all platform binaries as a fat binary for each configurations.
    # Calculate where the (multiple) built files are coming from:
    echo "Taking device build from: ${CURRENTCONFIG_DEVICE_DIR}"
    echo "Taking simulator build from: ${CURRENTCONFIG_SIMULATOR_DIR}"
    echo "...I will output a universal build to: ${CREATING_UNIVERSAL_DIR}"
    # ... remove the products of previous runs of this script
    #      NB: this directory is ONLY created by this script - it should be safe to delete!
    echo "lipo: for current configuration (${CONFIGURATION}) creating output file: ${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}"
    # Added: StackOverflow suggestion to also copy "include" files
    #    (untested, but should work OK)
    echo "Fetching headers from ${PUBLIC_HEADERS_FOLDER_PATH}"
    echo "  (if you embed your library project in another project, you will need to add"
    echo "   a "User Search Headers" build setting of: (NB INCLUDE THE DOUBLE QUOTES BELOW!)"
    echo '        "$(TARGET_BUILD_DIR)/usr/local/include/"'
    # * needs to be outside the double quotes?


    1. Create a static lib project
    2. Select the Target
    3. In "Build Settings" tab, set "Build Active Architecture Only" to "NO" (for all items)
    4. In "Build Phases" tab, select "Add ... New Build Phase ... New Run Script Build Phase"
    5. Copy/paste the script (above) into the box

    ...BONUS OPTIONAL usage:

    1. OPTIONAL: if you have headers in your library, add them to the "Copy Headers" phase
    2. OPTIONAL: ...and drag/drop them from the "Project" section to the "Public" section
    3. OPTIONAL: ...and they will AUTOMATICALLY be exported every time you build the app, into a sub-directory of the "debug-universal" directory (they will be in usr/local/include)
    4. OPTIONAL: NOTE: if you also try to drag/drop your project into another Xcode project, this exposes a bug in Xcode 4, where it cannot create an .IPA file if you have Public Headers in your drag/dropped project. The workaround: dont' embed xcode projects (too many bugs in Apple's code!)

    If you can't find the output file, here's a workaround:

    1. Add the following code to the very end of the script (courtesy of Frederik Wallner): open "${CREATING_UNIVERSAL_DIR}"

    2. Apple deletes all output after 200 lines. Select your Target, and in the Run Script Phase, you MUST untick: "Show environment variables in build log"

    3. if you're using a custom "build output" directory for XCode4, then XCode puts all your "unexpected" files in the wrong place.

      1. Build the project
      2. Click on the last icon on the right, in the top left area of Xcode4.
      3. Select the top item (this is your "most recent build". Apple should auto-select it, but they didn't think of that)
      4. in the main window, scroll to bottom. The very last line should read: lipo: for current configuration (Debug) creating output file: /Users/blah/Library/Developer/Xcode/DerivedData/AppName-ashwnbutvodmoleijzlncudsekyf/Build/Products/Debug-universal/libTargetName.a

      ...that is the location of your Universal Build.

    How to include "non sourcecode" files in your project (PNG, PLIST, XML, etc)

    1. Do everything above, check it works
    2. Create a new Run Script phase that comes AFTER THE FIRST ONE (copy/paste the code below)
    3. Create a new Target in Xcode, of type "bundle"
    4. In your MAIN PROJECT, in "Build Phases", add the new bundle as something it "depends on" (top section, hit the plus button, scroll to bottom, find the ".bundle" file in your Products)
    5. In your NEW BUNDLE TARGET, in "Build Phases", add a "Copy Bundle Resources" section, and drag/drop all the PNG files etc into it

    Script to auto-copy the built bundle(s) into same folder as your FAT static library:

    echo "RunScript2:"
    echo "Autocopying any bundles into the 'universal' output folder created by RunScript1"

    How to do a non-greedy match in grep?


    For non-greedy match in grep you could use a negated character class. In other words, try to avoid wildcards.

    For example, to fetch all links to jpeg files from the page content, you'd use:

    grep -o '"[^" ]\+.jpg"'

    To deal with multiple line, pipe the input through xargs first. For performance, use ripgrep.

    Flutter - The method was called on null

    You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

    One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.


    I see diegoveloper beat me to answering this, and that the OP asked a follow up.

    @Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

    CryptoListPresenter _presenter;
    void initState() {
      _presenter = new CryptoListPresenter(...);

    Best way to check if column returns a null value (from database to .net application)

    Use DBNull.Value.Equals on the object without converting it to a string.

    Here's an example:

       if (! DBNull.Value.Equals(row[fieldName])) 
          //not null

    Spring default behavior for lazy-init

    The default behaviour is false:

    By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

    I suggest reading up

    Google API authentication: Not valid origin for the client

    If you are running it on localhost change the port to 5000 and it will fix it

    Sending emails through SMTP with PHPMailer

    SMTP -> ERROR: EHLO not accepted from server:

    that's typical of trying to connect to a SSL service with a client that's not using SSL

    SMTP Error: Could not authenticate.

    no suprise there having failed to start an SMTP conversation authentigation is not an option,.

    phpmailer doesn't do implicit SSL (aka TLS on connect, SMTPS) Short of rewriting smtp.class.php to include support for it there it no way to do what you ask.

    Use port 587 with explicit SSL (aka TLS, STARTTLS) instead.

    jQuery SVG, why can't I addClass?

    Or just use old-school DOM methods when JQ has a monkey in the middle somewhere.

    var myElement = $('#my_element')[0];
    var myElClass = myElement.getAttribute('class').split(/\s+/g);
    //splits class into an array based on 1+ white space characters
    myElement.setAttribute('class', myElClass.join(' '));
    //$(myElement) to return to JQ wrapper-land

    Learn the DOM people. Even in 2016's framework-palooza it helps quite regularly. Also, if you ever hear someone compare the DOM to assembly, kick them for me.

    How to find schema name in Oracle ? when you are connected in sql session using read only user

    How about the following 3 statements?

    -- change to your schema


    -- check current schema


    -- generate drop table statements

    SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

    COPY the RESULT and PASTE and RUN.

    How to pass IEnumerable list to controller in MVC including checkbox state?

    Use a list instead and replace your foreach loop with a for loop:

    @model IList<BlockedIPViewModel>
    @using (Html.BeginForm()) 
        @for (var i = 0; i < Model.Count; i++) 
                    @Html.HiddenFor(x => x[i].IP)           
                    @Html.CheckBoxFor(x => x[i].Checked)
                    @Html.DisplayFor(x => x[i].IP)
            <input type="submit" value="Unblock IPs" />

    Alternatively you could use an editor template:

    @model IEnumerable<BlockedIPViewModel>
    @using (Html.BeginForm()) 
            <input type="submit" value="Unblock IPs" />

    and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

    @model BlockedIPViewModel
            @Html.HiddenFor(x => x.IP)
            @Html.CheckBoxFor(x => x.Checked)
            @Html.DisplayFor(x => x.IP)

    The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

    Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

    RegEx to exclude a specific string constant

    Try this regular expression:


    It describes three cases:

    1. less than three arbitrary character
    2. exactly three characters, while either
      • the first is not A, or
      • the first is A but the second is not B, or
      • the first is A, the second B but the third is not C
    3. more than three arbitrary characters

    Add a list item through javascript

    Try something like this:

    var node=document.createElement("LI");
    var textnode=document.createTextNode(firstname);


    How to add url parameters to Django template url tag?

    First you need to prepare your url to accept the param in the regex: (

    url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

    So you use this in your template:

    {% url 'panel_person_form' %}

    If you have more than one param, you can change your regex and modify the template using the following:

    {% url 'panel_person_form' group_id=3 %}

    jQuery autohide element after 5 seconds

    jQuery(".success_mgs").show(); setTimeout(function(){ jQuery(".success_mgs").hide();},5000);

    make UITableViewCell selectable only while editing

    Have you tried setting the selection properties of your tableView like this:

    tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

    If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

    Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

    You can have this method return nil in cases where you don't want the selection to happen.

    What is the difference between procedural programming and functional programming?

    To expand on Konrad's comment:

    As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined;

    Because of this, functional code is generally easier to parallelize. Since there are (generally) no side effects of the functions, and they (generally) just act on their arguments, a lot of concurrency issues go away.

    Functional programming is also used when you need to be capable of proving your code is correct. This is much harder to do with procedural programming (not easy with functional, but still easier).

    Disclaimer: I haven't used functional programming in years, and only recently started looking at it again, so I might not be completely correct here. :)

    else & elif statements not working in Python

    Python can generate same 'invalid syntax' error even if ident for 'elif' block not matching to 'if' block ident (tabs for the first, spaces for second or vice versa).

    Arguments to main in C

    Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

    #include <stdio.h>
    int main(int argc, char *argv[])
        printf("The following arguments were passed to main():\n");
        printf("argnum \t value \n");
        for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
        return 0;

    And output is similar to:

    The following arguments were passed to main():
    0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
    1        -P
    2        TestHostAttoshiba
    3        _http._tcp
    4        local
    5        80
    6        MyNewArgument
    8        type=NewHost
    9        test=yes
    10       result=output

    AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

    For me, I had to have OpenCV (3.4.2), Py-OpenCV (3.4.2), LibOpenCV (3.4.2).

    My Python was version 3.5.6 with Anaconda in Windows OS 10.

    Does React Native styles support gradients?

    React Native hasn't provided the gradient color yet. But still, you can do it with a nmp package called react-native-linear-gradient or you can click here for more info

    1. npm install react-native-linear-gradient --save
    2. use import LinearGradient from 'react-native-linear-gradient'; in your application file
    3.         <LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}>
                  Your Text Here

    Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

    Using Java 8 or above you can use an Optional and Java Streams.

    So you can simply use the JdbcTemplate.queryForList() method, create a Stream and use Stream.findFirst() which will return the first value of the Stream or an empty Optional:

    public Optional<String> test() {
        String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
        return jdbc.queryForList(sql, String.class)

    To improve the performance of the query you can append LIMIT 1 to your query, so not more than 1 item is transferred from the database.

    Phone: numeric keyboard for text input

    For me the best solution was:

    For integer numbers, which brings up the 0-9 pad on android and iphone

    <label for="ting">
    <input id="ting" name="ting" type="number" pattern="[\d]*" />

    You also may want to do this to hide the spinners in firefox/chrome/safari, most clients think they look ugly

     input[type=number]::-webkit-outer-spin-button {
          -webkit-appearance: none;
          margin: 0;
     input[type=number] {

    And add novalidate='novalidate' to your form element, if your doing custom validation

    Ps just in case you actually wanted floating point numbers after all,step to whatever precision you fancy, will add '.' to android

    <label for="ting">
    <input id="ting" name="ting" type="number" pattern="[\d\.]*" step="0.01" />

    Comparing floating point number to zero

    You are correct with your observation.

    If x == 0.0, then abs(x) * epsilon is zero and you're testing whether abs(y) <= 0.0.

    If y == 0.0 then you're testing abs(x) <= abs(x) * epsilon which means either epsilon >= 1 (it isn't) or x == 0.0.

    So either is_equal(val, 0.0) or is_equal(0.0, val) would be pointless, and you could just say val == 0.0. If you want to only accept exactly +0.0 and -0.0.

    The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".

    How to resolve git stash conflict without commit?

    No problem there. A simple git reset HEAD is what you're looking for because it leaves your files as modified just like a non-conflicting git stash pop.

    The only problem is that your conflicting files will still have the conflict tags and git will no longer report them as conflicting with the "both_modified" flag which is useful.

    To prevent this, just resolve the conflicts (edit and fix the conflicting files) before running git reset HEAD and you're good to go...

    At the end of this process your stash will remain in the queue, so just do a git stash drop to clear it up.

    This just happened to me and googled this question, so the solution has been tested.

    I think that's as clean as it gets...

    Single Line Nested For Loops

    The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

    Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

    >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

    >>> combs = []
    >>> for x in [1,2,3]:
    ...     for y in [3,1,4]:
    ...         if x != y:
    ...             combs.append((x, y))
    >>> combs
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

    On to your questions:

    What type must object be in order to use this for loop structure?

    An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

    What is the order in which i and j are assigned to elements in object?

    They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

    Can it be simulated by a different for loop structure?

    Yes, already shown above.

    Can this for loop be nested with a similar or different structure for loop? And how would it look?

    Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

    [[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

    #1045 - Access denied for user 'root'@'localhost' (using password: YES)

    1. Go to C:\xampp\phpMyAdmin

    2. Edit the file

    3. Replace $cfg['Servers'][$i]['auth_type'] = 'config'; by $cfg['Servers'][$i]['auth_type'] = 'cookie';

    For now on the PHPMyAdmin will ask you for your password, no more error.

    ERROR: Cannot open source file " "

    1. Copy the contents of the file,
    2. Create an .h file, give it the name of the original .h file
    3. Copy the contents of the original file to the newly created one
    4. Build it
    5. VOILA!!

    Merge 2 DataTables and store in a new one

    dtAll = dtOne.Copy();

    The parameter TRUE preserve the changes.

    For more details refer to MSDN.

    Most efficient way to find smallest of 3 numbers Java?

    Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, determines the smallest value and displays the result.

    How do I configure HikariCP in my Spring Boot app in my files?

    I came across HikariCP and I was amazed by the benchmarks and I wanted to try it instead of my default choice C3P0 and to my surprise I struggled to get the configurations right probably because the configurations differ based on what combination of tech stack you are using.

    I have setup Spring Boot project with JPA, Web, Security starters (Using Spring Initializer) to use PostgreSQL as a database with HikariCP as connection pooling.
    I have used Gradle as build tool and I would like to share what worked for me for the following assumptions:

    1. Spring Boot Starter JPA (Web & Security - optional)
    2. Gradle build too
    3. PostgreSQL running and setup with a database (i.e. schema, user, db)

    You need the following build.gradle if you are using Gradle or equivalent pom.xml if you are using maven

    buildscript {
        ext {
            springBootVersion = '1.5.8.RELEASE'
        repositories {
        dependencies {
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'war'
    group = 'com'
    version = '1.0'
    sourceCompatibility = 1.8
    repositories {
    dependencies {
        // Exclude the tomcat-jdbc since it's used as default for connection pooling
        // This can also be achieved by setting the spring.datasource.type to HikariCP 
        // datasource see below
        compile('org.springframework.boot:spring-boot-starter-data-jpa') {
            exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
        // Download HikariCP but, exclude hibernate-core to avoid version conflicts
        compile('com.zaxxer:HikariCP:2.5.1') {
            exclude group: 'org.hibernate', module: 'hibernate-core'
        // Need this in order to get the HikariCPConnectionProvider
        compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
            exclude group: 'com.zaxxer', module: 'HikariCP'
            exclude group: 'org.hibernate', module: 'hibernate-core'

    There are a bunch of excludes in the above build.gradle and that's because

    1. First exclude, instructs gradle that exclude the jdbc-tomcat connection pool when downloading the spring-boot-starter-data-jpa dependencies. This can be achieved by setting up the spring.datasource.type=com.zaxxer.hikari.HikariDataSource also but, I don't want an extra dependency if I don't need it
    2. Second exclude, instructs gradle to exclude hibernate-core when downloading com.zaxxer dependency and that's because hibernate-core is already downloaded by Spring Boot and we don't want to end up with different versions.
    3. Third exclude, instructs gradle to exclude hibernate-core when downloading hibernate-hikaricp module which is needed in order to make HikariCP use org.hibernate.hikaricp.internal.HikariCPConnectionProvider as connection provider instead of deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider

    Once I figured out the build.gradle and what to keep and what to not, I was ready to copy/paste a datasource configuration into my and expected everything to work with flying colors but, not really and I stumbled upon the following issues

    • Spring boot failing to find out database details (i.e. url, driver) hence, not able to setup jpa and hibernate (because I didn't name the property key values right)
    • HikariCP falling back to com.zaxxer.hikari.hibernate.HikariConnectionProvider
    • After instructing Spring to use new connection-provider for when auto-configuring hibernate/jpa then HikariCP failed because it was looking for some key/value in the and was complaining about dataSource, dataSourceClassName, jdbcUrl. I had to debug into HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider and found out that HikariCP could not find the properties from because it was named differently.

    Anyway, this is where I had to rely on trial and error and make sure that HikariCP is able to pick the properties (i.e. data source that's db details, as well as pooling properties) as well as Sping Boot behave as expected and I ended up with the following file.

    # Spring data source needed for Spring boot to behave
    # Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included 
    # in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
    # Hikari will use the above plus the following to setup connection pooling
    # Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
    # Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
    # So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up 
    # with different versions of hibernate-core 
    # JPA specific configs
    # Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP 

    As shown above the configurations are divided into categories based on following naming patterns

    • spring.datasource.x (Spring auto-configure will pick these, so will HikariCP)
    • spring.datasource.hikari.x (HikariCP picks these to setup the pool, make a note of the camelCase field names)
    • spring.jpa.hibernate.connection.provider_class (Instructs Spring to use new HibernateConnectionProvider)
    • (Used by Spring to auto-configure JPA, make a note of the field names with underscores)

    It's hard to come across a tutorial or post or some resource that shows how the above properties file is used and how the properties should be named. Well, there you have it.

    Throwing the above with build.gradle (or at least similar) into a Spring Boot JPA project version (1.5.8) should work like a charm and connect to your pre-configured database (i.e. in my case it's PostgreSQL that both HikariCP & Spring figure out from the spring.datasource.url on which database driver to use).

    I did not see the need to create a DataSource bean and that's because Spring Boot is capable of doing everything for me just by looking into and that's neat.

    The article in HikariCP's github wiki shows how to setup Spring Boot with JPA but, lacks explanation and details.

    The above two file is also availble as a public gist

    Should I use 'border: none' or 'border: 0'?

    Easiest Way to remove border with css

    border: 0;

    HTML embed autoplay="false", but still plays automatically

    the below codes helped me with the same problem. Let me know if it helped.

    <!DOCTYPE html>
    <audio controls>
    <source src="YOUR AUDIO FILE" type="audio/mpeg">
    Your browser does not support the audio element.

    multiprocessing: How do I share a dict among multiple processes?

    I'd like to share my own work that is faster than Manager's dict and is simpler and more stable than pyshmht library that uses tons of memory and doesn't work for Mac OS. Though my dict only works for plain strings and is immutable currently. I use linear probing implementation and store keys and values pairs in a separate memory block after the table.

    from mmap import mmap
    import struct
    from timeit import default_timer
    from multiprocessing import Manager
    from pyshmht import HashTable
    class shared_immutable_dict:
        def __init__(self, a):
            self.hs = 1 << (len(a) * 3).bit_length()
            kvp = self.hs * 4
            ht = [0xffffffff] * self.hs
            kvl = []
            for k, v in a.iteritems():
                h = self.hash(k)
                while ht[h] != 0xffffffff:
                    h = (h + 1) & (self.hs - 1)
                ht[h] = kvp
                kvp += self.kvlen(k) + self.kvlen(v)
            self.m = mmap(-1, kvp)
            for p in ht:
            for x in kvl:
                if len(x) <= 0x7f:
                    self.m.write(uint_format.pack(0x80000000 + len(x)))
        def hash(self, k):
            h = hash(k)
            h = (h + (h >> 3) + (h >> 13) + (h >> 23)) * 1749375391 & (self.hs - 1)
            return h
        def get(self, k, d=None):
            h = self.hash(k)
            while True:
                x = uint_format.unpack(self.m[h * 4:h * 4 + 4])[0]
                if x == 0xffffffff:
                    return d
                if k == self.read_kv():
                    return self.read_kv()
                h = (h + 1) & (self.hs - 1)
        def read_kv(self):
            sz = ord(self.m.read_byte())
            if sz & 0x80:
                sz = uint_format.unpack(chr(sz) +[0] - 0x80000000
        def kvlen(self, k):
            return len(k) + (1 if len(k) <= 0x7f else 4)
        def __contains__(self, k):
            return self.get(k, None) is not None
        def close(self):
    uint_format = struct.Struct('>I')
    def uget(a, k, d=None):
        return to_unicode(a.get(to_str(k), d))
    def uin(a, k):
        return to_str(k) in a
    def to_unicode(s):
        return s.decode('utf-8') if isinstance(s, str) else s
    def to_str(s):
        return s.encode('utf-8') if isinstance(s, unicode) else s
    def mmap_test():
        n = 1000000
        d = shared_immutable_dict({str(i * 2): '1' for i in xrange(n)})
        start_time = default_timer()
        for i in xrange(n):
            if bool(d.get(str(i))) != (i % 2 == 0):
                raise Exception(i)
        print 'mmap speed: %d gets per sec' % (n / (default_timer() - start_time))
    def manager_test():
        n = 100000
        d = Manager().dict({str(i * 2): '1' for i in xrange(n)})
        start_time = default_timer()
        for i in xrange(n):
            if bool(d.get(str(i))) != (i % 2 == 0):
                raise Exception(i)
        print 'manager speed: %d gets per sec' % (n / (default_timer() - start_time))
    def shm_test():
        n = 1000000
        d = HashTable('tmp', n)
        d.update({str(i * 2): '1' for i in xrange(n)})
        start_time = default_timer()
        for i in xrange(n):
            if bool(d.get(str(i))) != (i % 2 == 0):
                raise Exception(i)
        print 'shm speed: %d gets per sec' % (n / (default_timer() - start_time))
    if __name__ == '__main__':

    On my laptop performance results are:

    mmap speed: 247288 gets per sec
    manager speed: 33792 gets per sec
    shm speed: 691332 gets per sec

    simple usage example:

    ht = shared_immutable_dict({'a': '1', 'b': '2'})
    print ht.get('a')

    How to make a WPF window be on top of all other windows of my app (not system wide)?

    I just ran into the same problem and found trouble setting the owner using MVVM without causing the app to crash in production. I have a Window Manager View Model that includes a command to open a window using the uri of the window - and I wasn't able to set the owner to App.MainWindow without the app crashing.

    So - Instead of setting the owner, I bound the TopMost property of the window to a property in my Window Manager View model which indicates whether the application is currently active. If the application is active, the window is on top as I would like. If it is not active, other windows can cover it.

    Here is what I added to my View Model:

     public class WindowManagerVM : GalaSoft.MvvmLight.ViewModelBase
            public WindowManagerVM()
                App.Current.Activated += (s, e) => IsAppActive = true;
                App.Current.Deactivated += (s, e) => IsAppActive = false;
            private bool _isAppActive = true;
            public bool IsAppActive
                get => _isAppActive;
                    if (_isAppActive != value)
                        _isAppActive = value;
                        RaisePropertyChanged(() => IsAppActive);

    Here is the XAML that implements it (I use MVVM light with a ViewModelLocator as a static resource in my app called Locator):

    <Window Topmost="{Binding WindowManager.IsAppActive, Source={StaticResource Locator}}"/>

    Using CMake with GNU Make: How can I see the exact commands?

    I was trying something similar to ensure the -ggdb flag was present.

    Call make in a clean directory and grep the flag you are looking for. Looking for debug rather than ggdb I would just write.

    make VERBOSE=1 | grep debug

    The -ggdb flag was obscure enough that only the compile commands popped up.

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

    Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.

    #!/usr/bin/env sh
    import_cert() {
      local HOST=$1
      local PORT=$2
      # get the SSL certificate
      openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert
      # delete the old alias and then import the new one
      keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null
      # create a keystore and import certificate
      keytool -import -noprompt -trustcacerts \
          -alias ${HOST} -file ${HOST}.cert \
          -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}
      rm ${HOST}.cert
    import_cert 443
    import_cert 443
    import_cert 443 # google

    How do I modify fields inside the new PostgreSQL JSON datatype?

    UPDATE test
    SET data = data::jsonb - 'a' || '{"a":5}'::jsonb
    WHERE data->>'b' = '2'

    This seems to be working on PostgreSQL 9.5

    How to convert a char array back to a string?

    Try this


    How to use executeReader() method to retrieve the value of just one cell

    It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

    String sql = "SELECT ColumnNumber FROM learer WHERE = " + index;
    SqlCommand cmd = new SqlCommand(sql,conn);
    learerLabel.Text = (String) cmd.ExecuteScalar();

    Here is more information about Connecting to database and managing data.

    Move SQL data from one table to another

    Yes it is. First INSERT + SELECT and then DELETE orginals.

    INSERT INTO Table2 (UserName,Password)
    SELECT UserName,Password FROM Table1 WHERE UserName='X' AND Password='X'

    then delete orginals

    DELETE FROM Table1 WHERE UserName='X' AND Password='X'

    you may want to preserve UserID or someother primary key, then you can use IDENTITY INSERT to preserve the key.

    see more on SET IDENTITY_INSERT on MSDN

    Excel VBA Automation Error: The object invoked has disconnected from its clients

    I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.

    Simple CSS: Text won't center in a button

    Testing this in Chrome, you need to add

    padding: 0px;

    To the CSS.

    Implement touch using Python?

    Looks like this is new as of Python 3.4 - pathlib.

    from pathlib import Path

    This will create a file.txt at the path.


    Path.touch(mode=0o777, exist_ok=True)

    Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.

    submit a form in a new tab

    Try using jQuery

    <script type="text/javascript">
    $("form").submit(function() {
    $("form").attr('target', '_blank');
    return true;

    Here is a full answer -


    I'm betting you just need to refresh the datagrid. Try this:


    If this works... you might want to rethink this part of your application.

    openpyxl - adjust column width size

    I have a problem with merged_cells and autosize not work correctly, if you have the same problem, you can solve with the next code:

    for col in worksheet.columns:
        max_length = 0
        column = col[0].column # Get the column name
        for cell in col:
            if cell.coordinate in worksheet.merged_cells: # not check merge_cells
            try: # Necessary to avoid error on empty cells
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
        adjusted_width = (max_length + 2) * 1.2
        worksheet.column_dimensions[column].width = adjusted_width

    How to convert a full date to a short date in javascript?

    Here you go:

    (new Date()).toLocaleDateString('en-US');

    That's it !!

    you can use it on any date object

    let's say.. you have an object called "currentDate"

    var currentDate = new Date(); //use your date here
    currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy


    If you want it in local format then

    currentDate.toLocaleDateString(); // gives date in local Format

    How to select some rows with specific rownames from a dataframe?

    Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

    • students[1,2] would select row 1 and column 2, the result here would be a single cell.
    • students[1,] would select all of row 1, students[,2] would select all of column 2.

    If you'd like to select multiple rows or columns, use a list of values, like this:

    • students[c(1,3,4),] would select rows 1, 3 and 4,
    • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

    Hope I could help.

    How to enable CORS in AngularJs

    Try using the resource service to consume flickr jsonp:

    var MyApp = angular.module('MyApp', ['ng', 'ngResource']);
    MyApp.factory('flickrPhotos', function ($resource) {
        return $resource('', { format: 'json', jsoncallback: 'JSON_CALLBACK' }, { 'load': { 'method': 'JSONP' } });
    MyApp.directive('masonry', function ($parse) {
        return {
            restrict: 'AC',
            link: function (scope, elem, attrs) {
                elem.masonry({ itemSelector: '.masonry-item', columnWidth: $parse(attrs.masonry)(scope) });
    MyApp.directive('masonryItem', function () {
        return {
            restrict: 'AC',
            link: function (scope, elem, attrs) {
                elem.imagesLoaded(function () {
    MyApp.controller('MasonryCtrl', function ($scope, flickrPhotos) {
        $ = flickrPhotos.load({ tags: 'dogs' });


    <div class="masonry: 240;" ng-controller="MasonryCtrl">
        <div class="masonry-item" ng-repeat="item in photos.items">
            <img ng-src="{{ }}" />

    what is Ljava.lang.String;@

    Ljava.lang.String;@ is returned where you used string arrays as strings. Employee.getSelectCancel() does not seem to return a String[]

    How to check if a string contains only numbers?

    Use IsNumeric Function :


    If you want to validate a phone number you should use a regular expression, for example:

    ^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$

    How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

    Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

    I had a opened record set of the post that was created by:

    Set RecSet = Conn.Execute()

    This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

    Set RecSet = Nothing

    ...everything worked just fine.

    So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

    Is there a way to remove unused imports and declarations from Angular 2+?

    To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

    "compilerOptions": {
        "noUnusedLocals": true,
        "noUnusedParameters": true

    have the typescript compiler installed, ifnot install it with:

    npm install -g typescript

    and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

    I would also recomend using typescript hero extension for organizing your imports.

    changing the owner of folder in linux

    Use chown to change ownership and chmod to change rights.

    use the -R option to apply the rights for all files inside of a directory too.

    Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

    For example

    sudo chown -R username:group directory

    will change ownership (both user and group) of all files and directories inside of directory and directory itself.

    sudo chown username:group directory

    will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

    you need to use sudo to change the ownership from root to yourself.


    Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

    Also You can change the group ownership of a file or directory with the command:

    chgrp group_name file/directory_name

    You must be a member of the group to which you are changing ownership to.

    You can find group of file as follows

    # ls -l file
    -rw-r--r-- 1 root family 0 2012-05-22 20:03 file
    # chown sujit:friends file

    User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

    What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

    But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

    Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

    How to represent empty char in Java Character class

    char means exactly one character. You can't assign zero characters to this type.

    That means that there is no char value for which String.replace(char, char) would return a string with a diffrent length.

    jQuery: How can I create a simple overlay?

    Here is a simple javascript only solution

    function displayOverlay(text) {
        $("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
            "position": "fixed",
            "top": 0,
            "left": 0,
            "width": "100%",
            "height": "100%",
            "background-color": "rgba(0,0,0,.5)",
            "z-index": 10000,
            "vertical-align": "middle",
            "text-align": "center",
            "color": "#fff",
            "font-size": "30px",
            "font-weight": "bold",
            "cursor": "wait"
    function removeOverlay() {



    cout is not a member of std

    add #include <iostream> to the start of io.cpp too.

    How to play ringtone/alarm sound in Android

    public class AlarmReceiver extends WakefulBroadcastReceiver {
        public void onReceive(final Context context, Intent intent) {
            //this will update the UI with message
            Reminder inst = Reminder.instance();
            //this will sound the alarm tone
            //this will sound the alarm once, if you wish to
            //raise alarm in loop continuously then use MediaPlayer and setLooping(true)
            Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            if (alarmUri == null) {
                alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
            //this will send a notification message
            ComponentName comp = new ComponentName(context.getPackageName(),
            startWakefulService(context, (intent.setComponent(comp)));

    Tomcat Server not starting with in 45 seconds

    Well, I tried all the solutions:

    • increasing timeout seconds;
    • deleting the server instance in Eclipse along with the Run Config.

    None of them worked.


    • there was no breakpoint in my code;
    • I don't use any antivirus.

    I realized that some people - who had the same problem - were using Eclipse Helios (so was I).

    I switched to Eclipse Kepler and it worked perfectly.

    Maybe it can be a solution. I wanted to use Helios, but Kepler is okay.

    Difference between ProcessBuilder and Runtime.exec()

    Yes there is a difference.

    • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

    • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

    So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

    Extract year from date

    When you convert your variable to Date:

    date <-  as.Date('10/30/2018','%m/%d/%Y')

    you can then cut out the elements you want and make new variables, like year:

    year <- as.numeric(format(date,'%Y'))

    or month:

    month <- as.numeric(format(date,'%m'))

    Convert LocalDateTime to LocalDateTime in UTC

    public static String convertFromGmtToLocal(String gmtDtStr, String dtFormat, TimeZone lclTimeZone) throws Exception{
            if (gmtDtStr == null || gmtDtStr.trim().equals("")) return null;
            SimpleDateFormat format = new SimpleDateFormat(dtFormat);
            Date dt = format.parse(gmtDtStr);

    format.format(dt); }

    Renaming column names of a DataFrame in Spark Scala

    For those of you interested in PySpark version (actually it's same in Scala - see comment below) :

        merchants_df_renamed = merchants_df.toDF(
            'merchant_id', 'category', 'subcategory', 'merchant')


    |-- merchant_id: integer (nullable = true)
    |-- category: string (nullable = true)
    |-- subcategory: string (nullable = true)
    |-- merchant: string (nullable = true)

    What's the difference between map() and flatMap() methods in Java 8?

    If you think map() as an iteration(one level for loop), flatmap() is a two-level iteration(like a nested for loop). (Enter each iterated element foo, and do foo.getBarList() and iterate in that barList again)

    map(): take a stream, do something to every element, collect the single result of every process, output another stream. The definition of "do something function" is implicit. If the processment of any element results in null, null is used to compose the final stream. So, the number of elements in the resulting stream will be equal to number of input stream.

    flatmap(): take a stream of elements/streams and a function(explicit definition), apply the function to each element of each stream, and collect all the intermediate resulting stream to be a greater stream("flattening"). If the processment of any element results in null, empty stream is provided to the final step of "flattening". The number of elements in the resulting stream, is the total of all participating elements in all inputs, if the input is several streams.

    How to change line-ending settings

    For me what did the trick was running the command

    git config auto.crlf false

    inside the folder of the project, I wanted it specifically for one project.

    That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

        crlf = false

    at the end of the file. I suppose changing the file does the same trick as well.

    How to trim white space from all elements in array?

    In Java 8, Arrays.parallelSetAll seems ready made for this purpose:

    import java.util.Arrays;
    Arrays.parallelSetAll(array, (i) -> array[i].trim());

    This will modify the original array in place, replacing each element with the result of the lambda expression.

    How do you programmatically update query params in react-router?

    From DimitriDushkin on GitHub:

    import { browserHistory } from 'react-router';
     * @param {Object} query
    export const addQuery = (query) => {
      const location = Object.assign({}, browserHistory.getCurrentLocation());
      Object.assign(location.query, query);
      // or simple replace location.query if you want to completely change params
     * @param {...String} queryNames
    export const removeQuery = (...queryNames) => {
      const location = Object.assign({}, browserHistory.getCurrentLocation());
      queryNames.forEach(q => delete location.query[q]);


    import { withRouter } from 'react-router';
    import { addQuery, removeQuery } from '../../utils/utils-router';
    function SomeComponent({ location }) {
      return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
        <button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
        <button onClick={ () => removeQuery('paintRed')}>Paint white</button>
    export default withRouter(SomeComponent);

    Getting an odd error, SQL Server query using `WITH` clause

    In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

    SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
    INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

    And not:

    SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
    INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

    Twitter API returns error 215, Bad Authentication Data

    A very concise code without any other php file include of oauth etc. Please note to obtain following keys you need to sign up with and create application.

    $token = 'YOUR_TOKEN';
    $token_secret = 'YOUR_TOKEN_SECRET';
    $consumer_key = 'CONSUMER_KEY';
    $consumer_secret = 'CONSUMER_SECRET';
    $host = '';
    $method = 'GET';
    $path = '/1.1/statuses/user_timeline.json'; // api call path
    $query = array( // query parameters
        'screen_name' => 'twitterapi',
        'count' => '5'
    $oauth = array(
        'oauth_consumer_key' => $consumer_key,
        'oauth_token' => $token,
        'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
        'oauth_timestamp' => time(),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_version' => '1.0'
    $oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
    $query = array_map("rawurlencode", $query);
    $arr = array_merge($oauth, $query); // combine the values THEN sort
    asort($arr); // secondary sort (value)
    ksort($arr); // primary sort (key)
    // http_build_query automatically encodes, but our parameters
    // are already encoded, and must be by this point, so we undo
    // the encoding step
    $querystring = urldecode(http_build_query($arr, '', '&'));
    $url = "https://$host$path";
    // mash everything together for the text to hash
    $base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
    // same with the key
    $key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
    // generate the hash
    $signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
    // this time we're using a normal GET query, and we're only encoding the query params
    // (without the oauth params)
    $url .= "?".http_build_query($query);
    $url=str_replace("&amp;","&",$url); //Patch by @Frewuill
    $oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
    ksort($oauth); // probably not necessary, but twitter's demo does it
    // also not necessary, but twitter's demo does this too
    function add_quotes($str) { return '"'.$str.'"'; }
    $oauth = array_map("add_quotes", $oauth);
    // this is the full value of the Authorization line
    $auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
    // if you're doing post, you need to skip the GET building above
    // and instead supply query parameters to CURLOPT_POSTFIELDS
    $options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);
    // do our business
    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    $twitter_data = json_decode($json);
    foreach ($twitter_data as &$value) {
       $tweetout .= preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $value->text);
       $tweetout = preg_replace("/@(\w+)/", "<a href=\"\\1\" target=\"_blank\">@\\1</a>", $tweetout);
       $tweetout = preg_replace("/#(\w+)/", "<a href=\"\\1\" target=\"_blank\">#\\1</a>", $tweetout);
    echo $tweetout;


    Jquery bind double click and single click separately

    If you don't want to create separate variables to manage the state, you can check this answer

    @Cacheable key on multiple method arguments

    You can use a Spring-EL expression, for eg on JDK 1.7:

    @Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

    How to create a pulse effect using -webkit-animation - outward rings

    Or if you want a ripple pulse effect, you could use this:

    .gps_ring {
         border: 2px solid #fff;
         -webkit-border-radius: 50%;
         height: 18px;
         width: 18px;
         position: absolute;
        -webkit-animation: pulsate 1s ease-out;
        -webkit-animation-iteration-count: infinite; 
        opacity: 0.0;
    .gps_ring:before {
        border: 2px solid #fff;
        -webkit-border-radius: 50%;
        height: 30px;
        width: 30px;
        position: absolute;
        -webkit-animation: pulsate 1s ease-out;
        -webkit-animation-iteration-count: infinite; 
        -webkit-animation-delay: 0.1s;
        opacity: 0.0;
    .gps_ring:after {
        border:2px solid #fff;
        -webkit-border-radius: 50%;
        height: 50px;
        width: 50px;
        position: absolute;
        -webkit-animation: pulsate 1s ease-out;
        -webkit-animation-iteration-count: infinite; 
        -webkit-animation-delay: 0.2s;
        opacity: 0.0;
    @-webkit-keyframes pulsate {
        0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
        50% {opacity: 1.0;}
        100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}

    Sys is undefined

    I was using telerik and had exactly same problem.

    adding this to web.config resolved my issue :)

    <location path="Telerik.Web.UI.WebResource.axd">   
           <allow users="*"/>  

    maybe it will help you too. it was Authentication problem.


    Difference between View and ViewGroup in Android

    Viewgroup inherits properties of views and does more with other views and viewgroup.

    See the Android API:

    How to fix itunes could not connect to the iphone because an invalid response was received from the device?

    Try resetting your network settings

    Settings -> General -> Reset -> Reset Network Settings

    And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

    This one worked for me.

    What are the most common naming conventions in C?

    "Struct pointers" aren't entities that need a naming convention clause to cover them. They're just struct WhatEver *. DON'T hide the fact that there is a pointer involved with a clever and "obvious" typedef. It serves no purpose, is longer to type, and destroys the balance between declaration and access.

    In Python, how do I loop through the dictionary and change the value if it equals something?

    You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

    tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)

    Update - did some performance tests

    Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

    How Connect to remote host from Aptana Studio 3

    Window -> Show View -> Other -> Studio/Remote

    (Drag this tabbed window wherever)

    Click the add FTP button (see below); #profit

    Add New FTP Site...

    String.format() to format double in java

    String.format("%4.3f" , x) ;

    It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

    How to send data with angularjs $http.delete() request?

    I would suggest reading this url$resource

    and revaluate how you are calling your delete method of your resources.

    ideally you would want to be calling the delete of the resource item itself and by not passing the id of the resource into a catch all delete method

    however $http.delete accepts a config object that contains both url and data properties you could either craft the query string there or pass an object/string into the data

    maybe something along these lines

    $http.delete('/roles/'+roleid, {data: input});

    How do I view cookies in Internet Explorer 11 using Developer Tools

    How about typing document.cookie into the console? It just shows the values, but it's something.

    enter image description here

    operator << must take exactly one argument

    If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

    // Declarations
    struct MyObj;
    std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
    struct MyObj
        // This is a member unary-operator, hence one argument
        MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
        int value = 8;
    // This is a non-member binary-operator, 2 arguments
    std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
        return os << myObj.value;

    So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

    MyObj mo;
    // Calling the unary operator
    mo << std::cout;
    // which decomposes to...

    Or you could attempt to call the non-member binary operator:

    MyObj mo;
    // Calling the binary operator
    std::cout << mo;
    // which decomposes to...
    operator<<(std::cout, mo);

    You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

    Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

    Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

    struct MyObj
        // Note that we now return the ostream
        std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
        int value = 8;

    This syntax will irritate many coders now....

    MyObj mo;
    mo << std::cout << "Words words words";
    // this decomposes to...
    mo.operator<<(std::cout) << "Words words words";
    // ... or even further ...
    operator<<(mo.operator<<(std::cout), "Words words words");

    Note how the cout is the second argument in the chain here.... odd right?

    What is a race condition?

    Try this basic example for better understanding of race condition:

        public class ThreadRaceCondition {
         * @param args
         * @throws InterruptedException
        public static void main(String[] args) throws InterruptedException {
            Account myAccount = new Account(22222222);
            // Expected deposit: 250
            for (int i = 0; i < 50; i++) {
                Transaction t = new Transaction(myAccount,
                        Transaction.TransactionType.DEPOSIT, 5.00);
            // Expected withdrawal: 50
            for (int i = 0; i < 50; i++) {
                Transaction t = new Transaction(myAccount,
                        Transaction.TransactionType.WITHDRAW, 1.00);
            // Temporary sleep to ensure all threads are completed. Don't use in
            // realworld :-)
            // Expected account balance is 200
            System.out.println("Final Account Balance: "
                    + myAccount.getAccountBalance());
    class Transaction extends Thread {
        public static enum TransactionType {
            DEPOSIT(1), WITHDRAW(2);
            private int value;
            private TransactionType(int value) {
                this.value = value;
            public int getValue() {
                return value;
        private TransactionType transactionType;
        private Account account;
        private double amount;
         * If transactionType == 1, deposit else if transactionType == 2 withdraw
        public Transaction(Account account, TransactionType transactionType,
                double amount) {
            this.transactionType = transactionType;
            this.account = account;
            this.amount = amount;
        public void run() {
            switch (this.transactionType) {
            case DEPOSIT:
            case WITHDRAW:
                System.out.println("NOT A VALID TRANSACTION");
        public void deposit() {
        public void withdraw() {
        public void printBalance() {
                    + " : TransactionType: " + this.transactionType + ", Amount: "
                    + this.amount);
            System.out.println("Account Balance: "
                    + this.account.getAccountBalance());
    class Account {
        private int accountNumber;
        private double accountBalance;
        public int getAccountNumber() {
            return accountNumber;
        public double getAccountBalance() {
            return accountBalance;
        public Account(int accountNumber) {
            this.accountNumber = accountNumber;
        // If this method is not synchronized, you will see race condition on
        // Remove syncronized keyword to see race condition
        public synchronized boolean deposit(double amount) {
            if (amount < 0) {
                return false;
            } else {
                accountBalance = accountBalance + amount;
                return true;
        // If this method is not synchronized, you will see race condition on
        // Remove syncronized keyword to see race condition
        public synchronized boolean withdraw(double amount) {
            if (amount > accountBalance) {
                return false;
            } else {
                accountBalance = accountBalance - amount;
                return true;

    Create hyperlink to another sheet

    If you need to hyperlink Sheet1 to all or corresponding sheets, then use simple vba code. If you wish to create a radio button, then assign this macro to that button ex "Home Page".

    Here is it:

    Sub HomePage()
    ' HomePage Macro
    ' This is common code to go to sheet 1 if do not change name for Sheet1
    ' OR 
    ' You can write you sheet name here in case if its name changes
        Sheets("Monthly Reports Home").Select
    End Sub

    How can I use Bash syntax in Makefile targets?

    From the GNU Make documentation,

    5.3.1 Choosing the Shell
    The program used as the shell is taken from the variable `SHELL'.  If
    this variable is not set in your makefile, the program `/bin/sh' is
    used as the shell.

    So put SHELL := /bin/bash at the top of your makefile, and you should be good to go.

    BTW: You can also do this for one target, at least for GNU Make. Each target can have its own variable assignments, like this:

    all: a b
        @echo "a is $$0"
    b: SHELL:=/bin/bash   # HERE: this is setting the shell for b only
        @echo "b is $$0"

    That'll print:

    a is /bin/sh
    b is /bin/bash

    See "Target-specific Variable Values" in the documentation for more details. That line can go anywhere in the Makefile, it doesn't have to be immediately before the target.

    Java JTable getting the data of the selected row

    Just simple like this:

        tbl.addMouseListener(new MouseListener() {
            public void mouseReleased(MouseEvent e) {
            public void mousePressed(MouseEvent e) {
                String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            public void mouseExited(MouseEvent e) {
            public void mouseEntered(MouseEvent e) {
            public void mouseClicked(MouseEvent e) {

    Effects of the extern keyword on C functions

    The extern keyword informs the compiler that the function or variable has external linkage - in other words, that it is visible from files other than the one in which it is defined. In this sense it has the opposite meaning to the static keyword. It is a bit weird to put extern at the time of the definition, since no other files would have visibility of the definition (or it would result in multiple definitions). Normally you put extern in a declaration at some point with external visibility (such as a header file) and put the definition elsewhere.

    batch to copy files with xcopy

    If the requirement is to copy all files in "\Publish\Appfolder" into the parent "\Publish\" folder (inclusive of any subfolders, following works for me) The switch '/s' allows copying of all subfolders, recursively.

    xcopy src\main\Publish\Appfolder\*.* /s src\main\Publish\

    What's the canonical way to check for type in Python?

    For more complex type validations I like typeguard's approach of validating based on python type hint annotations:

    from typeguard import check_type
    from typing import List
        check_type('mylist', [1, 2], List[int])
    except TypeError as e:

    You can perform very complex validations in very clean and readable fashion.

    check_type('foo', [1, 3.14], List[Union[int, float]])
    # vs
    isinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) 

    jQuery - how to write 'if not equal to' (opposite of ==)

    if ("one" !== 1 )

    would evaluate as true, the string "one" is not equal to the number 1

    List of standard lengths for database fields

    I just queried my database with millions of customers in the USA.

    • The maximum first name length was 46. I go with 50. (Of course, only 500 of those were over 25, and they were all cases where data imports resulted in extra junk winding up in that field.)

    • Last name was similar to first name.

    • Email addresses maxed out at 62 characters. Most of the longer ones were actually lists of email addresses separated by semicolons.

    • Street address maxes out at 95 characters. The long ones were all valid.

    • Max city length was 35.

    This should be a decent statistical spread for people in the US. If you have localization to consider, the numbers could vary significantly.

    How do I get a button to open another activity?

    If you declared your button in the xml file similar to this:

            android:text="next activity"

    then you can use it to change the activity by putting this at the java file:

    public void goToActivity2 (View view){
        Intent intent = new Intent (this, Main2Activity.class);

    Note that my second activity is called "Main2Activity"

    Regex for Comma delimited list

    i used this for a list of items that had to be alphanumeric without underscores at the front of each item.


    Compiler warning - suggest parentheses around assignment used as truth value

    Be explicit - then the compiler won't warn that you perhaps made a mistake.

    while ( (list = list->next) != NULL )


    while ( (list = list->next) )

    Some day you'll be glad the compiler told you, people do make that mistake ;)

    Cross domain POST request is not sending cookie Ajax Jquery

    There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

    To have a cookie sent by the browser to another site during a request the following criteria must be met:

    A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

    Array.push() if does not exist?

    You can use the findIndex method with a callback function and its "this" parameter.

    Note: old browsers don't know findIndex but a polyfill is available.

    Sample code (take care that in the original question, a new object is pushed only if neither of its data is in previoulsy pushed objects):

    var a=[{name:"tom", text:"tasty"}], b;
    var magic=function(e) {
        return (( == || (e.text == this.text));
    b={name:"tom", text:"tasty"};
    if (a.findIndex(magic,b) == -1)
        a.push(b); // nothing done
    b={name:"tom", text:"ugly"};
    if (a.findIndex(magic,b) == -1)
        a.push(b); // nothing done
    b={name:"bob", text:"tasty"};
    if (a.findIndex(magic,b) == -1)
        a.push(b); // nothing done
    b={name:"bob", text:"ugly"};
    if (a.findIndex(magic,b) == -1)
        a.push(b); // b is pushed into a

    Check if Cookie Exists

    You can do something like this to find out the cookies's value:


    Binding a Button's visibility to a bool value in ViewModel

    In View:

     Height="50" Width="50"
     Style="{StaticResource MyButtonStyle}"
     Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
    Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>

    In view Model:

    public _advancedFormat = Visibility.visible (whatever you start with)
    public Visibility AdvancedFormat
     get{return _advancedFormat;}
       _advancedFormat = value;
       //raise property changed here

    You will need to have a property changed event

     protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
            PropertyChanged.Raise(this, e); 
        protected void OnPropertyChanged(string propertyName) 
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 

    This is how they use Model-view-viewmodel

    But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.

    Returning value from called function in a shell script

    A Bash function can't return a string directly like you want it to. You can do three things:

    1. Echo a string
    2. Return an exit status, which is a number, not a string
    3. Share a variable

    This is also true for some other shells.

    Here's how to do each of those options:

    1. Echo strings

        if mkdir "$lockdir"
        then # Directory did not exist, but it was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             echo >&2 "cannot acquire lock, giving up on $lockdir"
        echo "$retval"
    retval=$( testlock )
    if [ "$retval" == "true" ]
         echo "directory not created"
         echo "directory already created"

    2. Return exit status

        if mkdir "$lockdir"
        then # Directory did not exist, but was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             echo >&2 "cannot acquire lock, giving up on $lockdir"
        return "$retval"
    if [ "$retval" == 0 ]
         echo "directory not created"
         echo "directory already created"

    3. Share variable

        if mkdir "$lockdir"
        then # Directory did not exist, but it was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             echo >&2 "cannot acquire lock, giving up on $lockdir"
    if [ "$retval" == 0 ]
         echo "directory not created"
         echo "directory already created"

    How do I install a pip package globally instead of locally?

    Are you using virtualenv? If yes, deactivate the virtualenv. If you are not using, it is already installed widely (system level). Try to upgrade package.

    pip install flake8 --upgrade

    Webdriver and proxy server for firefox

    Here's a java example using DesiredCapabilities. I used it for pumping selenium tests into jmeter. (was only interested in HTTP requests)

    import org.openqa.selenium.Proxy;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;
    String myProxy = "localhost:7777";  //example: proxy host=localhost port=7777
    DesiredCapabilities capabilities = new DesiredCapabilities();
                               new Proxy().setHttpProxy(myProxy));
    WebDriver webDriver = new FirefoxDriver(capabilities); 

    std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

    The difference is that you can lock and unlock a std::unique_lock. std::lock_guard will be locked only once on construction and unlocked on destruction.

    So for use case B you definitely need a std::unique_lock for the condition variable. In case A it depends whether you need to relock the guard.

    std::unique_lock has other features that allow it to e.g.: be constructed without locking the mutex immediately but to build the RAII wrapper (see here).

    std::lock_guard also provides a convenient RAII wrapper, but cannot lock multiple mutexes safely. It can be used when you need a wrapper for a limited scope, e.g.: a member function:

    class MyClass{
        std::mutex my_mutex;
        void member_foo() {
            std::lock_guard<mutex_type> lock(this->my_mutex);            
             block of code which needs mutual exclusion (e.g. open the same 
             file in multiple threads).
            //mutex is automatically released when lock goes out of scope

    To clarify a question by chmike, by default std::lock_guard and std::unique_lock are the same. So in the above case, you could replace std::lock_guard with std::unique_lock. However, std::unique_lock might have a tad more overhead.

    Note that these days (since, C++17) one should use std::scoped_lock instead of std::lock_guard.

    How to get a div to resize its height to fit container?

    Another one simple method is there. You don't need to code more in CSS. Just including a java script and entering the div "id" inside the script you can get equal height of columns so that you can have the height fit to container. It works in major browsers.

    Source Code:

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <style type="text/css">
    *   {border:0; padding:0; margin:0;}/* Set everything to "zero" */
    #container {
        margin-left: auto;
        margin-right: auto;
        border: 1px solid black;
        overflow: auto;
        width: 800px;       
    #nav {
        width: 19%;
        border: 1px solid green;
    #content {
        width: 79%;
        border: 1px solid red;
    <script language="javascript">
    var ddequalcolumns=new Object()
    //Input IDs (id attr) of columns to equalize. Script will check if each corresponding column actually exists:
    ddequalcolumns.columnswatch=["nav", "content"]
    var tallest=0
    var resetit=(typeof reset=="string")? true : false
    for (var i=0; i<this.columnswatch.length; i++){
    if (document.getElementById(this.columnswatch[i])!=null){
    if (resetit)
    if (document.getElementById(this.columnswatch[i]).offsetHeight>tallest)
    if (tallest>0){
    for (var i=0; i<this.columnswatch.length; i++){
    if (document.getElementById(this.columnswatch[i])!=null)
    ddequalcolumns.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
    var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
    if (target.addEventListener)
    target.addEventListener(tasktype, functionref, false)
    else if (target.attachEvent)
    target.attachEvent(tasktype, functionref)
    ddequalcolumns.dotask(window, function(){ddequalcolumns.setHeights()}, "load")
    ddequalcolumns.dotask(window, function(){if (typeof ddequalcolumns.timer!="undefined") clearTimeout(ddequalcolumns.timer); ddequalcolumns.timer=setTimeout("ddequalcolumns.resetHeights()", 200)}, "resize")
    <div id=container>
        <div id=nav>
        <div id=content>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.</p>

    You can include any no of divs in this script.

    ddequalcolumns.columnswatch=["nav", "content"]

    modify in the above line its enough.

    Try this.

    Android JSONObject - How can I loop through a flat JSON object to get each key and value

    Use the keys() iterator to iterate over all the properties, and call get() for each.

    Iterator<String> iter = json.keys();
    while (iter.hasNext()) {
        String key =;
        try {
            Object value = json.get(key);
        } catch (JSONException e) {
            // Something went wrong!

    python time + timedelta equivalent


    t = time()
    t2 = time(t.hour+1, t.minute, t.second, t.microsecond)

    You can also omit the microseconds, if you don't need that much precision.

    Quantile-Quantile Plot using SciPy

    To add to the confusion around Q-Q plots and probability plots in the Python and R worlds, this is what the SciPy manual says:

    "probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot."

    If you try out scipy.stats.probplot, you'll see that indeed it compares a dataset to a theoretical distribution. Q-Q plots, OTOH, compare two datasets (samples).

    R has functions qqnorm, qqplot and qqline. From the R help (Version 3.6.3):

    qqnorm is a generic function the default method of which produces a normal QQ plot of the values in y. qqline adds a line to a “theoretical”, by default normal, quantile-quantile plot which passes through the probs quantiles, by default the first and third quartiles.

    qqplot produces a QQ plot of two datasets.

    In short, R's qqnorm offers the same functionality that scipy.stats.probplot provides with the default setting dist=norm. But the fact that they called it qqnorm and that it's supposed to "produce a normal QQ plot" may easily confuse users.

    Finally, a word of warning. These plots don't replace proper statistical testing and should be used for illustrative purposes only.

    How to fix Invalid byte 1 of 1-byte UTF-8 sequence


    InputStream inputStream= // Your InputStream from your database.
    Reader reader = new InputStreamReader(inputStream,"UTF-8");
    InputSource is = new InputSource(reader);
    saxParser.parse(is, handler);

    If it's anything else than UTF-8, just change the encoding part for the good one.

    Visual Studio debugging/loading very slow

    In my case the problem was an external running exe file - namely:


    under the name of

    "Windows Driver Foundation - User-mode Driver Companion Framework Host Process".

    Process, which has taken a steady 10% of the CPU. Killing it helped directly and withing a second the page has loaded.

    How to prevent a browser from storing passwords

    One way would be to generate random input names and work with them.

    This way, browsers will be presented with the new form each time and won't be able to pre-populate the input fields.

    If you provide us with some sample code (do you have a JavaScript single-page application (SPA) app or some server side rendering) I would be happy to help you in the implementation.

    ORDER BY the IN value list

    With Postgres 9.4 this can be done a bit shorter:

    select c.*
    from comments c
    join (
      select *
      from unnest(array[43,47,42]) with ordinality
    ) as x (id, ordering) on =
    order by x.ordering;

    Or a bit more compact without a derived table:

    select c.*
    from comments c
      join unnest(array[43,47,42]) with ordinality as x (id, ordering) 
        on =
    order by x.ordering

    Removing the need to manually assign/maintain a position to each value.

    With Postgres 9.6 this can be done using array_position():

    with x (id_list) as (
      values (array[42,48,43])
    select c.*
    from comments c, x
    where id = any (x.id_list)
    order by array_position(x.id_list,;

    The CTE is used so that the list of values only needs to be specified once. If that is not important this can also be written as:

    select c.*
    from comments c
    where id in (42,48,43)
    order by array_position(array[42,48,43],;

    how to add a jpg image in Latex

    You need to use a graphics library. Put this in your preamble:


    You can then add images like this:

    \caption{A simple caption \label{overflow}}

    This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

    And here we see figure \ref{overflow}.

    Read this guide here for a more detailed instruction:,_Figures_and_Captions

    How to call getResources() from a class which has no context?

    The normal solution to this is to pass an instance of the context to the class as you create it, or after it is first created but before you need to use the context.

    Another solution is to create an Application object with a static method to access the application context although that couples the Droid object fairly tightly into the code.

    Edit, examples added

    Either modify the Droid class to be something like this

     public Droid(Context context,int x, int y) {
        this.bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.birdpic);
        this.x = x;
        this.y = y;

    Or create an Application something like this:

    public class App extends
        private static App mApp = null;
        /* (non-Javadoc)
         * @see
        public void onCreate()
            mApp = this;
        public static Context context()
            return mApp.getApplicationContext();

    And call App.context() wherever you need a context - note however that not all functions are available on an application context, some are only available on an activity context but it will certainly do with your need for getResources().

    Please note that you'll need to add android:name to your application definition in your manifest, something like this:

        android:name=".App" >

    Android device is not connected to USB for debugging (Android studio)

    I am using Samung S8, I tried to install:

    1. Intel Android Driver
    2. Samsung USB driver

    But the adb bridge driver was still missing. I finally got it to work by installing the Samsung Smart Switch application which is a media manager application.

    Updated at 2018-04-20: If you are struggle with the driver, just use

    Using AngularJS date filter with UTC date

    You have also the possibility to write a custom filter for your date, that display it in UTC format. Note that I used toUTCString().

    var app = angular.module('myApp', []);_x000D_
    app.controller('dateCtrl', function($scope) {_x000D_
        $ = new Date();_x000D_
    app.filter('utcDate', function() {_x000D_
        return function(input) {_x000D_
           return input.toUTCString();_x000D_
    <script src=""></script>  _x000D_
    <div ng-app="myApp" ng-controller="dateCtrl">      _x000D_
        Today is {{today | utcDate}}       _x000D_

    mvn command not found in OSX Mavrerick

    Here is what worked for me.

    First of all I checked if M2_HOME variable is set env | grep M2_HOME. I've got nothing.

    I knew I had Maven installed in the folder "/usr/local/apache-maven-3.2.2", so executing the following 3 steps solved the problem for me:

    1. Set M2_HOME env variable


    1. Set M2 env variable


    1. Update the PATH

    export PATH=$M2:$PATH

    As mentioned above you can save that sequence in the .bash_profile file if you want it to be executed automatically.

    Check if string contains only whitespace

    Here is an answer that should work in all cases:

    def is_empty(s):
        "Check whether a string is empty"
        return not s or not s.strip()

    If the variable is None, it will stop at not sand not evaluate further (since not None == True). Apparently, the strip()method takes care of the usual cases of tab, newline, etc.

    How to install mcrypt extension in xampp

    First, you should download the suitable version for your system from here:

    Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

    What does -save-dev mean in npm install grunt --save-dev

    Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

    A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

    Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

    Can I add background color only for padding?

    I am sorry everyone that this is the solution the true one where you dont have to actually set the padding.

    What i have done...

    • Applied two gradients on background with both having one start and end color. Instead of using solid color. Reason being that you can't have two solid colors for one background.
    • Then applied different background-clip property to each.
    • thus making one color extend to content box and other to border, revealing the padding.

    Clever if i say so to myself.

    div {
        padding: 35px;
          linear-gradient(to bottom,
            rgba(240, 255, 40, 1) 0%,
            rgba(240, 255, 40, 1) 100%),
          linear-gradient(to bottom,
            rgba(240, 40, 40, 1) 0%,
            rgba(240, 40, 40, 1) 100%);
        background-clip: content-box, padding-box;

    Git error: src refspec master does not match any

    You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

     git add a_text_file.txt 

    ... do:

     git commit -m "Initial commit."

    ... and those errors should go away.

    How to uncheck checked radio button

    You might consider adding an additional radio button to each group labeled 'none' or the like. This can create a consistent user experience without complicating the development process.

    GoogleTest: How to skip a test?

    For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

    #include <gtest/gtest.h>
    const bool skip_some_test = true;
    bool some_test_was_run = false;
    void someTest() {
       some_test_was_run = true;
    TEST(BasicTest, Sanity) {
       EXPECT_EQ(1, 1);
       if(!skip_some_test) {

    This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

    Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

    As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

    The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

    You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

    Need to remove href values when printing in Chrome

    It doesn't. Somewhere in your print stylesheet, you must have this section of code:

    a[href]::after {
        content: " (" attr(href) ")"

    The only other possibility is you have an extension doing it for you.

    How can I perform a short delay in C# without using sleep?

    private void WaitNSeconds(int seconds)
        if (seconds < 1) return;
        DateTime _desired = DateTime.Now.AddSeconds(seconds);
        while (DateTime.Now < _desired) {

    Property 'value' does not exist on type 'Readonly<{}>'

    The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'

    Here is a good reference

    interface AppProps {
       //code related to your props goes here
    interface AppState {
       value: any
    class App extends React.Component<AppProps, AppState> {
      // ...