Programs & Examples On #Sqlexception

An exception that is thrown when the database driver encounters an error. This tag could be used for both C# `SqlExpection` and Java `SQLException`.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to catch a specific SqlException error?

If you want list of error messages met in Sql server, you can see with

SELECT *
FROM master.dbo.sysmessages

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I encountered this error once after omitting this statement from my transaction.

COMMIT TRANSACTION [MyTransactionName]

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.

You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.

To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').

For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I faced the same issue and solved it by setting the Collation to utf8_general_ci for each column.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

To further add missing points here, as per the request by Jaskey

Database version is stored within the SQLite database file.

catch is the constructor

SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

So when the database helper constructor is called with a name (2nd param), platform checks if the database exists or not and if the database exists, it gets the version information from the database file header and triggers the right call back

As already explained in the older answer, if the database with the name doesn't exists, it triggers onCreate.

Below explanation explains onUpgrade case with an example.

Say, your first version of application had the DatabaseHelper (extending SQLiteOpenHelper) with constructor passing version as 1 and then you provided an upgraded application with the new source code having version passed as 2, then automatically when the DatabaseHelper is constructed, platform triggers onUpgrade by seeing the file already exists, but the version is lower than the current version which you have passed.

Now say you are planing to give a third version of application with db version as 3 (db version is increased only when database schema is to be modified). In such incremental upgrades, you have to write the upgrade logic from each version incrementally for a better maintainable code

Example pseudo code below:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  switch(oldVersion) {
    case 1:
       //upgrade logic from version 1 to 2
    case 2:
       //upgrade logic from version 2 to 3
    case 3:
       //upgrade logic from version 3 to 4
       break;
    default:
       throw new IllegalStateException(
                "onUpgrade() with unknown oldVersion " + oldVersion);
  }
}

Notice the missing break statement in case 1 and 2. This is what I mean by incremental upgrade.

Say if the old version is 2 and new version is 4, then the logic will upgrade the database from 2 to 3 and then to 4

If old version is 3 and new version is 4, it will just run the upgrade logic for 3 to 4

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I can give you two advices:

  1. It seems you are using "LoadXml" instead of "Load" method. In some cases, it helps me.
  2. You have an encoding problem. Could you check the encoding of the XML file and write it?

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Java: Getting a substring from a string starting after a particular character

With Guava do this:

String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);

Eventually configure the Splitter and use

Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...

Also take a look into this article on guava Splitter and this article on guava Iterables

Java8: sum values from specific field of the objects in a list

You can do this method: "IntSummaryStatistics"

IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();

Use of "this" keyword in C++

Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:

Person::Person() {
    int age;
    this->age = 1;
}

Also, this:

Person::Person(int _age) {
    age = _age;
}

It is pretty bad style; if you need an initializer with the same name use this notation:

Person::Person(int age) : age(age) {}

More info here: https://en.cppreference.com/w/cpp/language/initializer_list

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

The best way to handle the LazyInitializationException is to use the JOIN FETCH directive:

Query query = session.createQuery("""
    select m
    from Model m
    join fetch m.modelType
    where modelGroup.id = :modelGroupId
    """
);

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

How do I wait until Task is finished in C#?

It waits for client.GetAsync("aaaaa");, but doesn't wait for result = Print(x)

Try responseTask.ContinueWith(x => result = Print(x)).Wait()

--EDIT--

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
responseTask.Wait();
Console.WriteLine("End");

Above code doesn't guarantee the output:

In task
In ContinueWith
End

But this does (see the newTask)

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
newTask.Wait();
Console.WriteLine("End");

make a header full screen (width) css

#header {
margin: 0;
padding: 0;
width: 100%;
background: xxxx;
}

#header #content {
margin: 0px auto;
width: 800px; /* or whatever */
}

<div id="header">
<div id="content">
stuff here
</div>
</div>

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

You Can Use [AllowHtml] To Your Project For Example

 [AllowHtml]
 public string Description { get; set; }

For Use This Code To Class Library You Instal This Package

Install-Package Microsoft.AspNet.Mvc

After Use This using

using System.Web.Mvc;

Location for session files in Apache/PHP

Non of the above worked for me using the IUS repo for CentOS 7 with PHP 7.2:

php -v
> PHP 7.2.30 (cli) (built: Apr 19 2020 00:32:29) ( NTS )

php -r 'echo session_save_path(), "\n";
> 

php -r 'echo sys_get_temp_dir(), "\n";'
> /tmp

However, sessions weren't saved in the /tmp folder, but in the /var/lib/php/mod_php/session/ folder:

ls /var/lib/php/mod_php/session/
> sess_3cebqoq314pcnc2jgqiu840h0k  sess_ck5dtaerol28fpctj6nutbn6fn  sess_i24lgt2v2l58op5kfmj1k6qb3h  sess_nek5q1alop8fkt84gliie91703
> sess_9ff74f4q5ihccnv6com2a8409t  sess_dvrt9fmfuolr8bqt9efdpcbj0d  sess_igdaksn26hm1s5nfvtjfb53pl7  sess_tgf5b7gkgno8kuvl966l9ce7nn

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

How to sum all the values in a dictionary?

You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

Example:

c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}

sum(list(c.values()))

Can I use break to exit multiple nested 'for' loops?

  while (i<n) {
    bool shouldBreakOuter = false;
    for (int j=i + 1; j<n; ++j) {
      if (someCondition) {
          shouldBreakOuter = true;
      }
    }

    if (shouldBreakOuter == true)
      break;

  }

Execute a command line binary with Node.js

I just wrote a Cli helper to deal with Unix/windows easily.

Javascript:

define(["require", "exports"], function (require, exports) {
    /**
     * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
     * Requires underscore or lodash as global through "_".
     */
    var Cli = (function () {
        function Cli() {}
            /**
             * Execute a CLI command.
             * Manage Windows and Unix environment and try to execute the command on both env if fails.
             * Order: Windows -> Unix.
             *
             * @param command                   Command to execute. ('grunt')
             * @param args                      Args of the command. ('watch')
             * @param callback                  Success.
             * @param callbackErrorWindows      Failure on Windows env.
             * @param callbackErrorUnix         Failure on Unix env.
             */
        Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
            if (typeof args === "undefined") {
                args = [];
            }
            Cli.windows(command, args, callback, function () {
                callbackErrorWindows();

                try {
                    Cli.unix(command, args, callback, callbackErrorUnix);
                } catch (e) {
                    console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
                }
            });
        };

        /**
         * Execute a command on Windows environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.windows = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(process.env.comspec, _.union(['/c', command], args));
                callback(command, args, 'Windows');
            } catch (e) {
                callbackError(command, args, 'Windows');
            }
        };

        /**
         * Execute a command on Unix environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.unix = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(command, args);
                callback(command, args, 'Unix');
            } catch (e) {
                callbackError(command, args, 'Unix');
            }
        };

        /**
         * Execute a command no matters what's the environment.
         *
         * @param command   Command to execute. ('grunt')
         * @param args      Args of the command. ('watch')
         * @private
         */
        Cli._execute = function (command, args) {
            var spawn = require('child_process').spawn;
            var childProcess = spawn(command, args);

            childProcess.stdout.on("data", function (data) {
                console.log(data.toString());
            });

            childProcess.stderr.on("data", function (data) {
                console.error(data.toString());
            });
        };
        return Cli;
    })();
    exports.Cli = Cli;
});

Typescript original source file:

 /**
 * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
 * Requires underscore or lodash as global through "_".
 */
export class Cli {

    /**
     * Execute a CLI command.
     * Manage Windows and Unix environment and try to execute the command on both env if fails.
     * Order: Windows -> Unix.
     *
     * @param command                   Command to execute. ('grunt')
     * @param args                      Args of the command. ('watch')
     * @param callback                  Success.
     * @param callbackErrorWindows      Failure on Windows env.
     * @param callbackErrorUnix         Failure on Unix env.
     */
    public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
        Cli.windows(command, args, callback, function () {
            callbackErrorWindows();

            try {
                Cli.unix(command, args, callback, callbackErrorUnix);
            } catch (e) {
                console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
            }
        });
    }

    /**
     * Execute a command on Windows environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(process.env.comspec, _.union(['/c', command], args));
            callback(command, args, 'Windows');
        } catch (e) {
            callbackError(command, args, 'Windows');
        }
    }

    /**
     * Execute a command on Unix environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(command, args);
            callback(command, args, 'Unix');
        } catch (e) {
            callbackError(command, args, 'Unix');
        }
    }

    /**
     * Execute a command no matters what's the environment.
     *
     * @param command   Command to execute. ('grunt')
     * @param args      Args of the command. ('watch')
     * @private
     */
    private static _execute(command, args) {
        var spawn = require('child_process').spawn;
        var childProcess = spawn(command, args);

        childProcess.stdout.on("data", function (data) {
            console.log(data.toString());
        });

        childProcess.stderr.on("data", function (data) {
            console.error(data.toString());
        });
    }
}

Example of use:

    Cli.execute(Grunt._command, args, function (command, args, env) {
        console.log('Grunt has been automatically executed. (' + env + ')');

    }, function (command, args, env) {
        console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');

    }, function (command, args, env) {
        console.error('------------- Unix "' + command + '" command failed too. ---------------');
    });

Batch command date and time in file name

Your question seems to be solved, but ...

I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.

It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.

Ok, perhaps it could be that I'm wrong.

How do you configure an OpenFileDialog to select folders?

I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file.

If you set its AcceptFiles value to false, then it operates in only accept folder mode.

You can download the source from GitHub here

docker run <IMAGE> <MULTIPLE COMMANDS>

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

Selecting data from two different servers in SQL Server

Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

  1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
  2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
  3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
  4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
  5. OPENQUERY: Doesn't support variables
  6. All are T-SQL solutions. Relatively easy to implement and set up
  7. All are dependent on connection between source and destionation which might affect performance and scalability

Unable to start MySQL server

See this post https://bugs.mysql.com/bug.php?id=67917 Sometimes a temp directory is missing. I had the same error like "InnoDB: Error: unable to create temporary file; errno: 2"

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

How to group subarrays by a column value?

I think this works better in PHP 5.5+

$IdVar = array_column($data, 'id');

Matrix multiplication using arrays

Try this,

public static Double[][] multiplicar(Double A[][],Double B[][]){
    Double[][] C= new Double[2][2];
    int i,j,k;
     for (i = 0; i < 2; i++) {
         for (j = 0; j < 2; j++) {
             C[i][j] = 0.00000;
         }
     }
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            for (k=0;k<2;k++){
                  C[i][j]+=(A[i][k]*B[k][j]);

            }

        }
    }
    return C;
}

Determining if an Object is of primitive type

you could determine if an object is wrapper type by beneath statements:

***objClass.isAssignableFrom(Number.class);***

and you could also determine a primitive object by using the isPrimitive() method

pandas get column average/mean

Do note that it needs to be in the numeric data type in the first place.

 import pandas as pd
 df['column'] = pd.to_numeric(df['column'], errors='coerce')

Next find the mean on one column or for all numeric columns using describe().

df['column'].mean()
df.describe()

Example of result from describe:

          column 
count    62.000000 
mean     84.678548 
std     216.694615 
min      13.100000 
25%      27.012500 
50%      41.220000 
75%      70.817500 
max    1666.860000

Change status bar text color to light in iOS 9 with Objective-C

Using a UINavigationController and setting its navigation bar's barStyle to .Black. past this line in your AppDelegate.m file.

navigationController.navigationBar.barStyle = UIBarStyleBlack;

If you are not using UINavigationController then add following code in your ViewController.m file.

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

And call the method to this line :

[self setNeedsStatusBarAppearanceUpdate];

How to disable Paste (Ctrl+V) with jQuery?

I tried this in my Angular project and it worked fine without jQuery.

<input type='text' ng-paste='preventPaste($event)'>

And in script part:

$scope.preventPaste = function(e){
   e.preventDefault();
   return false;
};

In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.

Query for documents where array size is greater than 1

You can use aggregate, too:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

// you add "size_of_name" to transit document and use it to filter the size of the name

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Set angular scope variable in markup

ngInit can help to initialize variables.

<div ng-app='app'>
    <div ng-controller="MyController" ng-init="myVar='test'">
        {{myVar}}
    </div>
</div>

jsfiddle example

What is an undefined reference/unresolved external symbol error and how do I fix it?

When your include paths are different

Linker errors can happen when a header file and its associated shared library (.lib file) go out of sync. Let me explain.

How do linkers work? The linker matches a function declaration (declared in the header) with its definition (in the shared library) by comparing their signatures. You can get a linker error if the linker doesn't find a function definition that matches perfectly.

Is it possible to still get a linker error even though the declaration and the definition seem to match? Yes! They might look the same in source code, but it really depends on what the compiler sees. Essentially you could end up with a situation like this:

// header1.h
typedef int Number;
void foo(Number);

// header2.h
typedef float Number;
void foo(Number); // this only looks the same lexically

Note how even though both the function declarations look identical in source code, but they are really different according to the compiler.

You might ask how one ends up in a situation like that? Include paths of course! If when compiling the shared library, the include path leads to header1.h and you end up using header2.h in your own program, you'll be left scratching your header wondering what happened (pun intended).

An example of how this can happen in the real world is explained below.

Further elaboration with an example

I have two projects: graphics.lib and main.exe. Both projects depend on common_math.h. Suppose the library exports the following function:

// graphics.lib    
#include "common_math.h" 
   
void draw(vec3 p) { ... } // vec3 comes from common_math.h

And then you go ahead and include the library in your own project.

// main.exe
#include "other/common_math.h"
#include "graphics.h"

int main() {
    draw(...);
}

Boom! You get a linker error and you have no idea why it's failing. The reason is that the common library uses different versions of the same include common_math.h (I have made it obvious here in the example by including a different path, but it might not always be so obvious. Maybe the include path is different in the compiler settings).

Note in this example, the linker would tell you it couldn't find draw(), when in reality you know it obviously is being exported by the library. You could spend hours scratching your head wondering what went wrong. The thing is, the linker sees a different signature because the parameter types are slightly different. In the example, vec3 is a different type in both projects as far as the compiler is concerned. This could happen because they come from two slightly different include files (maybe the include files come from two different versions of the library).

Debugging the linker

DUMPBIN is your friend, if you are using Visual Studio. I'm sure other compilers have other similar tools.

The process goes like this:

  1. Note the weird mangled name given in the linker error. (eg. draw@graphics@XYZ).
  2. Dump the exported symbols from the library into a text file.
  3. Search for the exported symbol of interest, and notice that the mangled name is different.
  4. Pay attention to why the mangled names ended up different. You would be able to see that the parameter types are different, even though they look the same in the source code.
  5. Reason why they are different. In the example given above, they are different because of different include files.

[1] By project I mean a set of source files that are linked together to produce either a library or an executable.

EDIT 1: Rewrote first section to be easier to understand. Please comment below to let me know if something else needs to be fixed. Thanks!

How to map an array of objects in React

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx

PHP list of specific files in a directory

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
        {
            $thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
        }
    }
    closedir($handle);
}

A simple way to look at the extension using substr and strrpos

Auto reloading python Flask app upon code changes

In test/development environments

The werkzeug debugger already has an 'auto reload' function available that can be enabled by doing one of the following:

app.run(debug=True)

or

app.debug = True

You can also use a separate configuration file to manage all your setup if you need be. For example I use 'settings.py' with a 'DEBUG = True' option. Importing this file is easy too;

app.config.from_object('application.settings')

However this is not suitable for a production environment.

Production environment

Personally I chose Nginx + uWSGI over Apache + mod_wsgi for a few performance reasons but also the configuration options. The touch-reload option allows you to specify a file/folder that will cause the uWSGI application to reload your newly deployed flask app.

For example, your update script pulls your newest changes down and touches 'reload_me.txt' file. Your uWSGI ini script (which is kept up by Supervisord - obviously) has this line in it somewhere:

touch-reload = '/opt/virtual_environments/application/reload_me.txt'

I hope this helps!

jQuery event for images loaded

You can use my plugin waitForImages to handle this...

$(document).waitForImages(function() {
   // Loaded.
});

The advantage of this is you can localise it to one ancestor element and it can optionally detect images referenced in the CSS.

This is just the tip of the iceberg though, check the documentation for more functionality.

How to loop through a directory recursively to delete files with certain extensions

If you can change the shell used to run the command, you can use ZSH to do the job.

#!/usr/bin/zsh

for file in /tmp/**/*
do
    echo $file
done

This will recursively loop through all files/folders.

Getting last day of the month in a given string date

You can make use of the plusMonths and minusDays methods in Java 8:

// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));

// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);

// Add one month, subtract one day 
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31

How to access Anaconda command prompt in Windows 10 (64-bit)

How to add anaconda installation directory to your PATH variables

1. open environmental variables window

Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).

Then click on environment variables

If you struggle with this step read this explanation.

2. Edit Path in the user environmental variables section and add three new entries:

  • D:\path\to\anaconda3
  • D:\path\to\anaconda3\Scripts
  • D:\path\to\anaconda3\Library\bin

D:\path\to\anaconda3 should be the folder where you have installed anaconda

Click [OK] on all opened windows.

If you did everything correctly, you can test a conda command by opening a new powershell window.

conda --version

This should output something like: conda 4.8.2

What is the proper way to test if a parameter is empty in a batch file?

One of the best semi solutions is to copy %1 into a variable and then use delayed expansion, as delayedExp. is always safe against any content.

set "param1=%~1"
setlocal EnableDelayedExpansion
if "!param1!"=="" ( echo it is empty )
rem ... or use the DEFINED keyword now
if defined param1 echo There is something

The advantage of this is that dealing with param1 is absolutly safe.

And the setting of param1 will work in many cases, like

test.bat hello"this is"a"test
test.bat you^&me

But it still fails with strange contents like

test.bat ^&"&

To be able to get a 100% correct answer for the existence

It detects if %1 is empty, but for some content it can't fetch the content.
This can be also be useful to distinguish between an empty %1 and one with "".
It uses the ability of the CALL command to fail without aborting the batch file.

@echo off
setlocal EnableDelayedExpansion
set "arg1="
call set "arg1=%%1"

if defined arg1 goto :arg_exists

set "arg1=#"
call set "arg1=%%1"
if "!arg1!" EQU "#" (
    echo arg1 exists, but can't assigned to a variable
    REM Try to fetch it a second time without quotes
    (call set arg1=%%1)
    goto :arg_exists
)

echo arg1 is missing
exit /b

:arg_exists
echo arg1 exists, perhaps the content is '!arg1!'

If you want to be 100% bullet proof to fetch the content, you could read How to receive even the strangest command line parameters?

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

How to give the background-image path in CSS?

There are two basic ways:

url(../../images/image.png)

or

url(/Web/images/image.png)

I prefer the latter, as it's easier to work with and works from all locations in the site (so useful for inline image paths too).

Mind you, I wouldn't do so much deep nesting of folders. It seems unnecessary and makes life a bit difficult, as you've found.

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

Storing and Retrieving ArrayList values from hashmap

The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:

map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);

According to Map.computeIfAbsent docs:

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null

The most idiomatic way to iterate a map of lists is using Map.forEach and Iterable.forEach:

map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));

Or, as shown in other answers, a traditional for loop:

for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
    String k = e.getKey();
    for (Integer v : e.getValue()) {
        /* use k and v here */
    }
}

Logo image and H1 heading on the same line

If your image is part of the logo why not do this:

<h1><img src="img/logo.png" alt="logo" /> My website name</h1>

Use CSS to style it better.

And it is also best practice to make your logo a hyperlink that take the user back to the home page.

So you could do:

<h1 id="logo"><a href="/"><img src="img/logo.png" alt="logo" /> My website name</a></h1>

Appending pandas dataframes generated in a for loop

Use pd.concat to merge a list of DataFrame into a single big DataFrame.

appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    # store DataFrame in list
    appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet 
appended_data.to_excel('appended.xlsx')

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

How to create strings containing double quotes in Excel formulas?

I use a function for this (if the workbook already has VBA).

Function Quote(inputText As String) As String
  Quote = Chr(34) & inputText & Chr(34)
End Function

This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:

="Maurice "&Quote("Rocket")&" Richard"

This is similar to what Dave DuPlantis posted.

Remove or uninstall library previously added : cocoapods

The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:

  1. Install clean:

    $ sudo gem install cocoapods-clean
    
  2. Run deintegrate in the folder of the project:

    $ pod deintegrate
    
  3. Clean (this tool is no longer available):

    $ pod clean
    
  4. Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:

    $ pod install
    

Done.

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

How to send email in ASP.NET C#

You can try this using hotmail like this:-

MailMessage o = new MailMessage("From", "To","Subject", "Body");
NetworkCredential netCred= new NetworkCredential("Sender Email","Sender Password");
SmtpClient smtpobj= new SmtpClient("smtp.live.com", 587); 
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);

How can I sort a dictionary by key?

Found another way:

import json
print json.dumps(d, sort_keys = True)

upd:
1. this also sorts nested objects (thanks @DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.

How can I save a screenshot directly to a file in Windows?

Might I suggest WinSnap http://www.ntwind.com/software/winsnap/download-free-version.html. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.

Modifying list while iterating

I guess this is what you want:

l  = range(100)  
index = 0                       
for i in l:                         
    print i,              
    try:
        print l.pop(index+1),                  
        print l.pop(index+1)
    except:
        pass
    index += 1

It is quite handy to code when the number of item to be popped is a run time decision. But it runs with very a bad efficiency and the code is hard to maintain.

How to store printStackTrace into a string

You can use the ExceptionUtils.getStackTrace(Throwable t); from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

Code example:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}

How to write new line character to a file in Java

Put this code wherever you want to insert a new line:

bufferedWriter.newLine();

How do I upload a file with metadata using a REST web service?

I realize this is a very old question, but hopefully this will help someone else out as I came upon this post looking for the same thing. I had a similar issue, just that my metadata was a Guid and int. The solution is the same though. You can just make the needed metadata part of the URL.

POST accepting method in your "Controller" class:

public Task<HttpResponseMessage> PostFile(string name, float latitude, float longitude)
{
    //See http://stackoverflow.com/a/10327789/431906 for how to accept a file
    return null;
}

Then in whatever you're registering routes, WebApiConfig.Register(HttpConfiguration config) for me in this case.

config.Routes.MapHttpRoute(
    name: "FooController",
    routeTemplate: "api/{controller}/{name}/{latitude}/{longitude}",
    defaults: new { }
);

SSRS expression to format two decimal places does not show zeros

You need to make sure that the first numeral to the right of the decimal point is always displayed. In custom format strings, # means display the number if it exists, and 0 means always display something, with 0 as the placeholder.

So in your case you will need something like:

=Format(Fields!CUL1.Value, "#,##0.##")

This saying: display 2 DP if they exist, for the non-zero part always display the lowest part, and use , as the grouping separator.

This is how it looks on your data (I've added a large value as well for reference):

enter image description here

If you're not interested in separating thousands, millions, etc, just use #0.## as Paul-Jan suggested.

The standard docs for Custom Numeric Format Strings are your best reference here.

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

PHP header() redirect with POST variables

Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:

if(correct){
    header("Location: passed.php");
} else {
    $smarty->assign("variables", $_POST);
    $smarty->display("register_error.php");
    exit;
}

I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.

If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it

ex.

register.php?name=mr_jones&address==......
echo $_GET[name];

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

How to send control+c from a bash script?

Ctrl+C sends a SIGINT signal.

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

# Terminates the program (like Ctrl+C)
kill -INT 888
# Force kill
kill -9 888

Assuming 888 is your process ID.


Note that kill 888 sends a SIGTERM signal, which is slightly different, but will also ask for the program to stop. So if you know what you are doing (no handler bound to SIGINT in the program), a simple kill is enough.

To get the PID of the last command launched in your script, use $! :

# Launch script in background
./my_script.sh &
# Get its PID
PID=$!
# Wait for 2 seconds
sleep 2
# Kill it
kill $PID

Angular no provider for NameService

You could also have the dependencies declared in the bootstrap-command like:

bootstrap(MyAppComponent,[NameService]);

At least that's what worked for me in alpha40.

this is the link: http://www.syntaxsuccess.com/viewarticle/dependency-injection-in-angular-2.0

Center button under form in bootstrap

Remove that <p> tag and add the button inside a <div class="form-actions"> like this:

<div class="form-actions">
    <button type="submit" class="btn">Confirm</button>
</div>

an then augment the CSS class with:

.form-actions {
    margin: 0;
    background-color: transparent;
    text-align: center;
}

Here's a JS Bin demo: http://jsbin.com/ijozof/2


Look for form-actions at the Bootstrap doc here:

http://twitter.github.io/bootstrap/base-css.html#buttons

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message when trying "hello world" like things with Qt. The problems went away by correctly running the qt moc (meta object compiler) and compiling+including these moc-generated files correctly.

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

Creating a Jenkins environment variable using Groovy

My environment was prior tooling such as Jenkins and was running with batch files (I know, I'm old). So those batch files (and their sub-batch files) are using environment variables. This was my piece of groovy script which injects environment variables. The names and parameters used are dummy ones.

// The process/batch which uses environment variables
def buildLabel = "SomeVersionNr"
def script = "startBuild.bat"
def processBuilder = new ProcessBuilder(script, buildLabel)

//Inject our environment variables
Map<String, String> env = processBuilder.environment()
env.put("ProjectRoot", "someLocation")
env.put("SomeVar", "Some")

Process p = processBuilder.start()
p.waitFor()

Of course if you set Jenkins up from scratch you would probably do it differently and share the variables in another way, or pass parameters around but this might come handy.

How can I read numeric strings in Excel cells as string (not numbers)?

As already mentioned in the Poi's JavaDocs (https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29) don't use:

cell.setCellType(Cell.CELL_TYPE_STRING);

but use:

DataFormatter df = new DataFormatter();
String value = df.formatCellValue(cell);

More examples on http://massapi.com/class/da/DataFormatter.html

JavaScript before leaving the page

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function () {
            if (isDirty) {
                return "There are unsaved data.";
            }
            return undefined;
        }

returning "undefined" will disable the confirmation

Note: returning "null" will not work with IE

Also you can use "undefined" to disable the confirmation

window.onbeforeunload = undefined;

Setting the User-Agent header for a WebClient request

I found that the WebClient kept removing my User-Agent header after one request and I was tired of setting it each time. I used a hack to set the User-Agent permanently by making my own custom WebClient and overriding the GetWebRequest method. Hope this helps.

public class CustomWebClient : WebClient
{
    public CustomWebClient(){}

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        request.UserAgent="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0;)";

        //... your other custom code...

        return request;
    }
}

jQuery Screen Resolution Height Adjustment

To get screen resolution in JS use screen object

screen.height;
screen.width;

Based on that values you can calculate your margin to whatever suits you.

How can I get the assembly file version

When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used

versionlabel.Text = "Version " + Application.ProductVersion;

This approach requires a reference to System.Windows.Forms.

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Another corner case that this could happen: if you read/write a JAR file through a URL and later try to delete the same file within the same JVM session.

File f = new File("/tmp/foo.jar");
URL j = f.toURI().toURL();

URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
URLConnection c = u.openConnection();

// open a Jar entry in auto-closing manner
try (InputStream i = c.getInputStream()) {

    // just read some stuff; for demonstration purposes only
    byte[] first16 = new byte[16];
    i.read(first16);
    System.out.println(new String(first16));
}

// ...

// i is now closed, so we should be good to delete the jar; but...
System.out.println(f.delete());     // says false!

Reason is that the internal JAR file handling logic of Java, tends to cache JarFile entries:

// inner class of `JarURLConnection` that wraps the actual stream returned by `getInputStream()`

class JarURLInputStream extends FilterInputStream {
    JarURLInputStream(InputStream var2) {
        super(var2);
    }

    public void close() throws IOException {
        try {
            super.close();
        } finally {

            // if `getUseCaches()` is set, `jarFile` won't get closed!

            if (!JarURLConnection.this.getUseCaches()) {
                JarURLConnection.this.jarFile.close();
            }
        }
    }
}

And each JarFile (rather, the underlying ZipFile structure) would hold a handle to the file, right from the time of construction up until close() is invoked:

public ZipFile(File file, int mode, Charset charset) throws IOException {
    // ...

    jzfile = open(name, mode, file.lastModified(), usemmap);

    // ...
}

// ...

private static native long open(String name, int mode, long lastModified,
                                boolean usemmap) throws IOException;

There's a good explanation on this NetBeans issue.


Apparently there are two ways to "fix" this:

  • You can disable the JAR file caching - for the current URLConnection, or for all future URLConnections (globally) in the current JVM session:

    URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
    URLConnection c = u.openConnection();
    
    // for only c
    c.setUseCaches(false);
    
    // globally; for some reason this method is not static,
    // so we still need to access it through a URLConnection instance :(
    c.setDefaultUseCaches(false);
    
  • [HACK WARNING!] You can manually purge the JarFile from the cache when you are done with it. The cache manager sun.net.www.protocol.jar.JarFileFactory is package-private, but some reflection magic can get the job done for you:

    class JarBridge {
    
        static void closeJar(URL url) throws Exception {
    
            // JarFileFactory jarFactory = JarFileFactory.getInstance();
            Class<?> jarFactoryClazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
            Method getInstance = jarFactoryClazz.getMethod("getInstance");
            getInstance.setAccessible(true);
            Object jarFactory = getInstance.invoke(jarFactoryClazz);
    
            // JarFile jarFile = jarFactory.get(url);
            Method get = jarFactoryClazz.getMethod("get", URL.class);
            get.setAccessible(true);
            Object jarFile = get.invoke(jarFactory, url);
    
            // jarFactory.close(jarFile);
            Method close = jarFactoryClazz.getMethod("close", JarFile.class);
            close.setAccessible(true);
            //noinspection JavaReflectionInvocation
            close.invoke(jarFactory, jarFile);
    
            // jarFile.close();
            ((JarFile) jarFile).close();
        }
    }
    
    // and in your code:
    
    // i is now closed, so we should be good to delete the jar
    JarBridge.closeJar(j);
    System.out.println(f.delete());     // says true, phew.
    

Please note: All this is based on Java 8 codebase (1.8.0_144); they may not work with other / later versions.

Shell script to send email

top -b -n 1 | mail -s "any subject" [email protected]

Pandas: Setting no. of max rows

It was already pointed in this comment and in this answer, but I'll try to give a more direct answer to the question:

from IPython.display import display
import numpy as np
import pandas as pd

n = 100
foo = pd.DataFrame(index=range(n))
foo['floats'] = np.random.randn(n)

with pd.option_context("display.max_rows", foo.shape[0]):
    display(foo)

pandas.option_context is available since pandas 0.13.1 (pandas 0.13.1 release notes). According to this,

[it] allow[s] you to execute a codeblock with a set of options that revert to prior settings when you exit the with block.

how to hide keyboard after typing in EditText in android?

You might also want to define the imeOptions within the EditText. This way, the keyboard will go away once you press on Done:

<EditText
    android:id="@+id/editText1"
    android:inputType="text"
    android:imeOptions="actionDone"/>

sql delete statement where date is greater than 30 days

Use DATEADD in your WHERE clause:

...
WHERE date < DATEADD(day, -30, GETDATE())

You can also use abbreviation d or dd instead of day.

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

How to grant remote access permissions to mysql server for user?

In my case I was trying to connect to a remote mysql server on cent OS. After going through a lot of solutions (granting all privileges, removing ip bindings,enabling networking) problem was still not getting solved.

As it turned out, while looking into various solutions,I came across iptables, which made me realize mysql port 3306 was not accepting connections.

Here is a small note on how I checked and resolved this issue.

  • Checking if port is accepting connections:
telnet (mysql server ip) [portNo]

-Adding ip table rule to allow connections on the port:

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

-Would not recommend this for production environment, but if your iptables are not configured properly, adding the rules might not still solve the issue. In that case following should be done:

service iptables stop

Hope this helps.

"inappropriate ioctl for device"

Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.

How to import other Python files?

There are many ways to import a python file, all with their pros and cons.

Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.

I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print("vixens cry")
    
  2. Get into the python interpreter:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print "where are the nuclear wessels?"
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. Run it like this:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    from riaa import *
    watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    computers are transforming into a noose and a yoke for humans
    

    That imports everything in the foreign file from a different directory.

Example 5, use os.system("python yourfile.py")

import os
os.system("python yourfile.py")

Example 6, import your file via piggybacking the python startuphook:

Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.pythonrc.py

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

Put this code into your main.py (can be anywhere):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

Run it, you should get this:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.

Example 7, Most Robust: Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. Make an empty file named __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. Run it:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!
    

    The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131

python: urllib2 how to send cookie with urlopen request

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

How to change value of ArrayList element in java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

How do I exit a while loop in Java?

You can do multiple condition logical tests within the while() check using the same rules as within any logical check.

while ( obj != null ) {  
    // do stuff  
}

works, as does

while ( value > 5 && value < 10 ) {  
    // do stuff  
}  

are valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;

while ( value > 5 ) {  
    if ( value > 10 ) { break; }  
    ...  
}  

Named parameters in JDBC

To avoid including a large framework, I think a simple homemade class can do the trick.

Example of class to handle named parameters:

public class NamedParamStatement {
    public NamedParamStatement(Connection conn, String sql) throws SQLException {
        int pos;
        while((pos = sql.indexOf(":")) != -1) {
            int end = sql.substring(pos).indexOf(" ");
            if (end == -1)
                end = sql.length();
            else
                end += pos;
            fields.add(sql.substring(pos+1,end));
            sql = sql.substring(0, pos) + "?" + sql.substring(end);
        }       
        prepStmt = conn.prepareStatement(sql);
    }

    public PreparedStatement getPreparedStatement() {
        return prepStmt;
    }
    public ResultSet executeQuery() throws SQLException {
        return prepStmt.executeQuery();
    }
    public void close() throws SQLException {
        prepStmt.close();
    }

    public void setInt(String name, int value) throws SQLException {        
        prepStmt.setInt(getIndex(name), value);
    }

    private int getIndex(String name) {
        return fields.indexOf(name)+1;
    }
    private PreparedStatement prepStmt;
    private List<String> fields = new ArrayList<String>();
}

Example of calling the class:

String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();

Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.

How to use clock() in C++

you can measure how long your program works. The following functions help measure the CPU time since the start of the program:

  • C++ (double)clock() / CLOCKS PER SEC with ctime included.
  • python time.clock() returns floating-point value in seconds.
  • Java System.nanoTime() returns long value in nanoseconds.

my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

so you can add this line of code after your algorithm

cout << (double)clock() / CLOCKS_PER_SEC ;

Expected Output: the output representing the number of clock ticks per second

How to make rectangular image appear circular with CSS

Building on the answer from @fzzle - to achieve a circle from a rectangle without defining a fixed height or width, the following will work. The padding-top:100% keeps a 1:1 ratio for the circle-cropper div. Set an inline background image, center it, and use background-size:cover to hide any excess.

CSS

.circle-cropper {
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
  border-radius: 50%;
  width: 100%;
  padding-top: 100%;
}

HTML

<div class="circle-cropper" role="img" style="background-image:url(myrectangle.jpg);"></div>

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

How to use pip with Python 3.x alongside Python 2.x

Thought this is old question, I think I have better solution

  1. To use pip for a python 2.x environment, use this command -

    py -2 -m pip install -r requirements.txt

  2. To use pip for python 3.x environment, use this command -

    py -3 -m pip install -r requirements.txt

duplicate 'row.names' are not allowed error

I used read_csv from the readr package

In my experience, the parameter row.names=NULL in the read.csv function will lead to a wrong reading of the file if a column name is missing, i.e. every column will be shifted.

read_csv solves this.

Is it possible to serialize and deserialize a class in C++?

You can check the amef protocol, an example of C++ encoding in amef would be like,

    //Create a new AMEF object
    AMEFObject *object = new AMEFObject();

    //Add a child string object
    object->addPacket("This is the Automated Message Exchange Format Object property!!","adasd");   

    //Add a child integer object
    object->addPacket(21213);

    //Add a child boolean object
    object->addPacket(true);

    AMEFObject *object2 = new AMEFObject();
    string j = "This is the property of a nested Automated Message Exchange Format Object";
    object2->addPacket(j);
    object2->addPacket(134123);
    object2->addPacket(false);

    //Add a child character object
    object2->addPacket('d');

    //Add a child AMEF Object
    object->addPacket(object2);

    //Encode the AMEF obejct
    string str = new AMEFEncoder()->encode(object,false);

Decoding in java would be like,

    string arr = amef encoded byte array value;
    AMEFDecoder decoder = new AMEFDecoder()
    AMEFObject object1 = AMEFDecoder.decode(arr,true);

The Protocol implementation has codecs for both C++ and Java, the interesting part is it can retain object class representation in the form of name value pairs, I required a similar protocol in my last project, when i incidentally stumbled upon this protocol, i had actually modified the base library according to my requirements. Hope this helps you.

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

How to handle query parameters in angular 2

According to Angular2 documentation you should use:

@RouteConfig([
   {path: '/login/:token', name: 'Login', component: LoginComponent},
])

@Component({ template: 'login: {{token}}' })
class LoginComponent{
   token: string;
   constructor(params: RouteParams) {
      this.token = params.get('token');
   }
}

Flexbox Not Centering Vertically in IE

i have updated both fiddles. i hope it will make your work done.

centering

    html, body
{
    height: 100%;
    width: 100%;
}

body
{
    margin: 0;
}

.outer
{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inner
{
    width: 80%;
    margin: 0 auto;
}

center and scroll

html, body
    {
        height: 100%;
        width: 100%;
    }

    body
    {
        margin: 0;
        display:flex;
    }

    .outer
    {
        min-width: 100%;  
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .inner
    {
        width: 80%;
    margin-top:40px;
    margin: 0 auto;
    }

What is Haskell used for in the real world?

From the Haskell Wiki:

Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. This page collects resources on the industrial use of Haskell.

According to Wikipedia, the Haskell language was created out of the need to consolidate existing functional languages into a common one which could be used for future research in functional-language design.

It is apparent based on the information available that it has outgrown it's original purpose and is used for much more than research. It is now considered a general purpose functional programming language.

If you're still asking yourself, "Why should I use it?", then read the Why use it? section of the Haskell Wiki Introduction.

How to get the first column of a pandas DataFrame as a Series?

From v0.11+, ... use df.iloc.

In [7]: df.iloc[:,0]
Out[7]: 
0    1
1    2
2    3
3    4
Name: x, dtype: int64

Make first letter of a string upper case (with maximum performance)

Possible solution to resolve your problem .

   public static string FirstToUpper(this string lowerWord)
   {
       if (string.IsNullOrWhiteSpace(lowerWord) || string.IsNullOrEmpty(lowerWord))
            return lowerWord;
       return new StringBuilder(lowerWord.Substring(0, 1).ToUpper())
                 .Append(lowerWord.Substring(1))
                 .ToString();
   }

Call An Asynchronous Javascript Function Synchronously

You can force asynchronous JavaScript in NodeJS to be synchronous with sync-rpc.

It will definitely freeze your UI though, so I'm still a naysayer when it comes to whether what it's possible to take the shortcut you need to take. It's not possible to suspend the One And Only Thread in JavaScript, even if NodeJS lets you block it sometimes. No callbacks, events, anything asynchronous at all will be able to process until your promise resolves. So unless you the reader have an unavoidable situation like the OP (or, in my case, are writing a glorified shell script with no callbacks, events, etc.), DO NOT DO THIS!

But here's how you can do this:

./calling-file.js

var createClient = require('sync-rpc');
var mySynchronousCall = createClient(require.resolve('./my-asynchronous-call'), 'init data');

var param1 = 'test data'
var data = mySynchronousCall(param1);
console.log(data); // prints: received "test data" after "init data"

./my-asynchronous-call.js

function init(initData) {
  return function(param1) {
    // Return a promise here and the resulting rpc client will be synchronous
    return Promise.resolve('received "' + param1 + '" after "' + initData + '"');
  };
}
module.exports = init;

LIMITATIONS:

These are both a consequence of how sync-rpc is implemented, which is by abusing require('child_process').spawnSync:

  1. This will not work in the browser.
  2. The arguments to your function must be serializable. Your arguments will pass in and out of JSON.stringify, so functions and non-enumerable properties like prototype chains will be lost.

Calculate cosine similarity given 2 sentence strings

A simple pure-Python implementation would be:

import math
import re
from collections import Counter

WORD = re.compile(r"\w+")


def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
    sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator


def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)


text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."

vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)

cosine = get_cosine(vector1, vector2)

print("Cosine:", cosine)

Prints:

Cosine: 0.861640436855

The cosine formula used here is described here.

This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.

You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There is a javascript library DNS-JS.com that does just this.

DNS.Query("dns-js.com",
    DNS.QueryType.A,
    function(data) {
        console.log(data);
});

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

Error #2032: Stream Error

This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5

Equivalent of Clean & build in Android Studio?

It is probably not a correct way for clean, but I made that to delete unnecessary files, and take less size of a project. It continuously finds and deletes all build and Gradle folders made file clean.bat copy that into the folder where your project is

  set mypath=%cd% 
    for /d /r %mypath% %%a in (build\) do if exist "%%a" rmdir /s /q "%%a"
    for /d /r %mypath% %%a in (.gradle\) do if exist "%%a" rmdir /s /q "%%a"

MS-access reports - The search key was not found in any record - on save

Another possible cause of this error is a mismatched workgroup file. That is, if you try to use a secured (or partially-secured) MDB with a workgroup file other than the one used to secure it, you can trigger the error (I've seen it myself, years ago with Access 2000).

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

How to configure port for a Spring Boot application

Since Spring Boot provides various configuration externalization mechanism (through various PropertySource implementations and/or processors wired into Environment object in order), you can set any property outside of your jar archive through following methods:

  1. Pass property through command line argument as application argument

    java -jar <path/to/my/jar> --server.port=7788
    
  2. From property in SPRING_APPLICATION_JSON (Spring Boot 1.3.0+)

    • Define environment variable in U*IX shell:

      SPRING_APPLICATION_JSON='{"server.port":7788}' java -jar <path/to/my/jar>
      
    • By using Java system property:

      java -Dspring.application.json='{"server.port":7788}' -jar <path/to/my/jar>
      
    • Pass through command line argument:

      java -jar <path/to/my/jar> --spring.application.json='{"server.port":7788}'
      
  3. Define JVM system property

    java -Dserver.port=7788 -jar <path/to/my/jar>
    
  4. Define OS environment variable

    • U*IX Shell

      SERVER_PORT=7788 java -jar <path/to/my/jar>
      
    • Windows

      SET SERVER_PORT=7788
      java -jar <path/to/my/jar>
      
  5. Place property in ./config/application.properties configuration file

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  6. Place property in ./config/application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    
  7. Place property in ./application.properties

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  8. Place property in ./application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    

You can combine above methods all together, and the former configuration in the list take precedence over the latter one.

For example:

SERVER_PORT=2266 java -Dserver.port=5566 -jar <path/to/my/jar> --server.port=7788

The server will start and listen on port 7788.

This is very useful providing default properties in PropertySources with lower precedence (and usually packaged in the archive or coded in the source), and then override it in the runtime environment. And it is the design philosophy of Spring Boot:

Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.


SERVER_NAME to server.name conversion was done by Relaxed Binding.

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

How to find all positions of the maximum value in a list?

Here is the max value and the indexes it appears at:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
...     d[x].append(i)
... 
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]

Later: for the satisfaction of @SilentGhost

>>> from itertools import takewhile
>>> import heapq
>>> 
>>> def popper(heap):
...     while heap:
...         yield heapq.heappop(heap)
... 
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>> 
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]

Converting string to number in javascript/jQuery

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

AngularJS routing without the hash '#'

Lets write answer that looks simple and short

In Router at end add html5Mode(true);

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

In html head add base tag

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

thanks To @plus- for detailing the above answer

Javascript array value is undefined ... how do I test for that

You are checking it the array index contains a string "undefined", you should either use the typeof operator:

typeof predQuery[preId] == 'undefined'

Or use the undefined global property:

predQuery[preId] === undefined

The first way is safer, because the undefined global property is writable, and it can be changed to any other value.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How does one convert a HashMap to a List in Java?

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
    System.out.println(s);
}

how to extract only the year from the date in sql server 2008?

---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
insert into Users values(4,'9/10/1991')

select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, 
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, 
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users

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

You may want to try the following:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r;

The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command.

Test case:

CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);

Test query:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r
WHERE   l.score > 50;

Result:

+----------+----------+-------+------------+
| position | username | score | row_number |
+----------+----------+-------+------------+
|        3 | c        |    75 |          1 |
|        5 | e        |    55 |          2 |
|        6 | f        |    80 |          3 |
+----------+----------+-------+------------+
3 rows in set (0.00 sec)

Android Imagebutton change Image OnClick

<ImageButton android:src="@drawable/image_btn_src" ... />

image_btn_src.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
</selector>

How to update a value, given a key in a hashmap?

Java 8 way:

You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one.

For example,

Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));

Alternatevely, you could use merge method, where 1 is the default value and function increments existing value by 1:

words.merge("hello", 1, Integer::sum);

In addition, there is a bunch of other useful methods, such as putIfAbsent, getOrDefault, forEach, etc.

Insert new column into table in sqlite?

You can add new column with the query

ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)

But it will be added at the end, not in between the existing columns.

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

Boolean Field in Oracle

A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number type):

ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);

This creates a new column in my_table_name called my_new_boolean_column with default values of 0. The column will not accept NULL values and restricts the accepted values to either 0 or 1.

Copying a HashMap in Java

There is a small (HUGE) understatement here. If you want to copy a HashMap with nested structures, HashMap.putAll() will copy by reference, because it doesn't know how to exactly copy your object. For example:

import java.util.*;
class Playground {
    public static void main(String[ ] args) {
        Map<Integer, Map<Integer,List<Float>>> dataA = new HashMap<>();
        Map<Integer, Map<Integer,List<Float>>> dataB = new HashMap<>();

        dataA.put(1, new HashMap<>());
        dataB.putAll(dataA);

        assert(dataB.get(1).size() == 0);

        dataA.get(1).put(2, new ArrayList<>());

        if (dataB.get(1).size() == 1) { // true
            System.out.println(
                "Sorry object reference was copied - not the values");
        }
    }
}

So basically you will need to copy the fields yourself like here

List <Float> aX = new ArrayList<>(accelerometerReadingsX);
List <Float> aY = new ArrayList<>(accelerometerReadingsY);

List <Float> gX = new ArrayList<>(gyroscopeReadingsX);
List <Float> gY = new ArrayList<>(gyroscopeReadingsY);

Map<Integer, Map<Integer, Float>> readings = new HashMap<>();

Map<Integer,List<Float>> accelerometerReadings = new HashMap<>();
accelerometerReadings.put(X_axis, aX);
accelerometerReadings.put(Y_axis, aY);
readings.put(Sensor.TYPE_ACCELEROMETER, accelerometerReadings);

Map<Integer,List<Float>> gyroscopeReadings = new HashMap<>();
gyroscopeReadings.put(X_axis, gX);
gyroscopeReadings.put(Y_axis, gY);
readings.put(Sensor.TYPE_GYROSCOPE, gyroscopeReadings);

How to create a trie in Python

Modified from senderle's method (above). I found that Python's defaultdict is ideal for creating a trie or a prefix tree.

from collections import defaultdict

class Trie:
    """
    Implement a trie with insert, search, and startsWith methods.
    """
    def __init__(self):
        self.root = defaultdict()

    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
        current = self.root
        for letter in word:
            current = current.setdefault(letter, {})
        current.setdefault("_end")

    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
        current = self.root
        for letter in word:
            if letter not in current:
                return False
            current = current[letter]
        if "_end" in current:
            return True
        return False

    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
        current = self.root
        for letter in prefix:
            if letter not in current:
                return False
            current = current[letter]
        return True

# Now test the class

test = Trie()
test.insert('helloworld')
test.insert('ilikeapple')
test.insert('helloz')

print test.search('hello')
print test.startsWith('hello')
print test.search('ilikeapple')

How to exclude a directory from ant fileset, based on directories contents

You need to add a '/' after the dir name

<exclude name="WEB-INF/" />

How to iterate through range of Dates in Java?

Java 8 style, using the java.time classes:

// Monday, February 29 is a leap day in 2016 (otherwise, February only has 28 days)
LocalDate start = LocalDate.parse("2016-02-28"),
          end   = LocalDate.parse("2016-03-02");

// 4 days between (end is inclusive in this example)
Stream.iterate(start, date -> date.plusDays(1))
        .limit(ChronoUnit.DAYS.between(start, end) + 1)
        .forEach(System.out::println);

Output:

2016-02-28
2016-02-29
2016-03-01
2016-03-02

Alternative:

LocalDate next = start.minusDays(1);
while ((next = next.plusDays(1)).isBefore(end.plusDays(1))) {
    System.out.println(next);
}

Java 9 added the datesUntil() method:

start.datesUntil(end.plusDays(1)).forEach(System.out::println);

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

Conda activate not working?

In the windows environment use "anaconda prompt" instead of "command prompt".

Component based game engine design

Interesting artcle...

I've had a quick hunt around on google and found nothing, but you might want to check some of the comments - plenty of people seem to have had a go at implementing a simple component demo, you might want to take a look at some of theirs for inspiration:

http://www.unseen-academy.de/componentSystem.html
http://www.mcshaffry.com/GameCode/thread.php?threadid=732
http://www.codeplex.com/Wikipage?ProjectName=elephant

Also, the comments themselves seem to have a fairly in-depth discussion on how you might code up such a system.

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

Maven Jacoco Configuration - Exclude classes/packages from report not working

Another solution:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <executions>
        <execution>
            <id>default-prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>default-report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>default-check</id>
            <goals>
                <goal>check</goal>
            </goals>
            <configuration>
                <rules>
                    <rule implementation="org.jacoco.maven.RuleConfiguration">
                        <excludes>
                            <exclude>com.mypackage1</exclude
                            <exclude>com.mypackage2</exclude>
                        </excludes>
                        <element>PACKAGE</element>
                        <limits>
                            <limit implementation="org.jacoco.report.check.Limit">
                                <counter>COMPLEXITY</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>0.85</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </execution>
    </executions>
</plugin>

Please note that, we are using "<element>PACKAGE</element>" in the configuration which then helps us to exclude at package level.

jQuery event to trigger action when a div is made visible

The following code (pulled from http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/) will enable you to use $('#someDiv').on('show', someFunc);.

(function ($) {
  $.each(['show', 'hide'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
      this.trigger(ev);
      return el.apply(this, arguments);
    };
  });
})(jQuery);

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How can I initialize an array without knowing it size?

Just return any kind of list. ArrayList will be fine, its not static.

    ArrayList<yourClass> list = new ArrayList<yourClass>();
for (yourClass item : yourArray) 
{
   list.add(item); 
}

Reduce left and right margins in matplotlib plot

With recent matplotlib versions you might want to try Constrained Layout.

Too bad pandas does not handle it well...

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

Comparing two byte arrays in .NET

P/Invoke powers activate!

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, long count);

static bool ByteArrayCompare(byte[] b1, byte[] b2)
{
    // Validate buffers are the same length.
    // This also ensures that the count does not exceed the length of either buffer.  
    return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;
}

What does Html.HiddenFor do?

And to consume the hidden ID input back on your Edit action method:

[HttpPost]
public ActionResult Edit(FormCollection collection)
{
    ViewModel.ID = Convert.ToInt32(collection["ID"]);
}

Returning http 200 OK with error within response body

No, this is very incorrect.

HTTP is an application protocol. 200 implies that the response contains a payload that represents the status of the requested resource. An error message usually is not a representation of that resource.

If something goes wrong while processing GET, the right status code is 4xx ("you messed up") or 5xx ("I messed up").

DataGrid get selected rows' column values

After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

Turning multi-line string into single comma-separated

You can use grep:

grep -o "+\S\+" in.txt | tr '\n' ','

which finds the string starting with +, followed by any string \S\+, then convert new line characters into commas. This should be pretty quick for large files.

How to set a background image in Xcode using swift?

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Reason : Old versions of Tomcat 6 JSP compiler don't seem to be aware of JDK 8 constant pool enhancements - eg. method handles. New code in JDK 8u is using a method handle instead of creating an anonymous class. This will cause the method handle to be listed in the constant pool and the eclipse compiler will choke on this - https://bz.apache.org/bugzilla/show_bug.cgi?id=56613

How do I set default values for functions parameters in Matlab?

Yes, it might be really nice to have the capability to do as you have written. But it is not possible in MATLAB. Many of my utilities that allow defaults for the arguments tend to be written with explicit checks in the beginning like this:

if (nargin<3) or isempty(myParameterName)
  MyParameterName = defaultValue;
elseif (.... tests for non-validity of the value actually provided ...)
  error('The sky is falling!')
end

Ok, so I would generally apply a better, more descriptive error message. See that the check for an empty variable allows the user to pass in an empty pair of brackets, [], as a placeholder for a variable that will take on its default value. The author must still supply the code to replace that empty argument with its default value though.

My utilities that are more sophisticated, with MANY parameters, all of which have default arguments, will often use a property/value pair interface for default arguments. This basic paradigm is seen in the handle graphics tools in matlab, as well as in optimset, odeset, etc.

As a means to work with these property/value pairs, you will need to learn about varargin, as a way of inputing a fully variable number of arguments to a function. I wrote (and posted) a utility to work with such property/value pairs, parse_pv_pairs.m. It helps you to convert property/value pairs into a matlab structure. It also enables you to supply default values for each parameter. Converting an unwieldy list of parameters into a structure is a VERY nice way to pass them around in MATLAB.

Get DOS path instead of Windows path

for %I in (.) do echo %~sI

Any simpler way?

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>

How to enable DataGridView sorting when user clicks on the column header?

I have a BindingList<> object bind as a data source to dataGridView.

BindingList x1;
x1 = new BindingList<sourceObject>();
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;

When I clicked the column header, no sorting takes place. I used the SortableBindingList answer provided by Tom Bushell. Having included two source files into my project

  1. SortableBindingList.cs
  2. PropertyComparer.cs

Then this change is made to my code:

Be.Timvw.Framework.ComponentModel.SortableBindingList x1;                       // 1
x1 = new Be.Timvw.Framework.ComponentModel.SortableBindingList<sourceObject>(); // 2
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;

After these changes I performed a build on my program. I am now able to sort by clicking the column headers. Only two lines need changing, they are highlighted in the code snippet above by trailing comments.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Is it possible to change the package name of an Android app on Google Play?

From Dianne Hackborn:

Things That Cannot Change:

The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.

More on things you cannot change here

Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.

how to add value to a tuple?

Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:

list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'), 
 ('2', '3', '4', '5', '2345'), 
 ('3', '4', '5', '6', '3456'), 
 ('4', '5', '6', '7', '4567')]

Replacing objects in array

Considering that the accepted answer is probably inefficient for large arrays, O(nm), I usually prefer this approach, O(2n + 2m):

function mergeArrays(arr1 = [], arr2 = []){
    //Creates an object map of id to object in arr1
    const arr1Map = arr1.reduce((acc, o) => {
        acc[o.id] = o;
        return acc;
    }, {});
    //Updates the object with corresponding id in arr1Map from arr2, 
    //creates a new object if none exists (upsert)
    arr2.forEach(o => {
        arr1Map[o.id] = o;
    });

    //Return the merged values in arr1Map as an array
    return Object.values(arr1Map);
}

Unit test:

it('Merges two arrays using id as the key', () => {
   var arr1 = [{id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'}];
   var arr2 = [{id:'124',name:'ttt'}, {id:'45',name:'yyy'}];
   const actual = mergeArrays(arr1, arr2);
   const expected = [{id:'124',name:'ttt'}, {id:'589',name:'www'}, {id:'45',name:'yyy'}, {id:'567',name:'rrr'}];
   expect(actual.sort((a, b) => (a.id < b.id)? -1: 1)).toEqual(expected.sort((a, b) => (a.id < b.id)? -1: 1));
})

PHP form - on submit stay on same page

You have to use code similar to this:

echo "<div id='divwithform'>";

if(isset($_POST['submit']))  // if form was submitted (if you came here with form data)
{
    echo "Success";
}
else                // if form was not submitted (if you came here without form data)
{
    echo "<form> ... </form>";
} 

echo "</div>";

Code with if like this is typical for many pages, however this is very simplified.

Normally, you have to validate some data in first "if" (check if form fields were not empty etc).

Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.

Remove scrollbars from textarea

Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:

<textarea style="overflow:auto"></textarea>

Or

<textarea style="overflow:hidden"></textarea>

...As suggested above

You can also try adding this, I never used it before, just saw it posted on a site today:

<textarea style="resize:none"></textarea>

This last option would remove the ability to resize the textarea. You can find more information on the CSS resize property here

How do I import CSV file into a MySQL table?

Change servername,username, password,dbname,path of your file, tablename and the field which is in your database you want to insert

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "bd_dashboard";
    //For create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    $query = "LOAD DATA LOCAL INFILE 
                'C:/Users/lenovo/Desktop/my_data.csv'
                INTO TABLE test_tab
                FIELDS TERMINATED BY ','
                LINES TERMINATED BY '\n'
                IGNORE 1 LINES
                (name,mob)";
    if (!$result = mysqli_query($conn, $query)){
        echo '<script>alert("Oops... Some Error occured.");</script>';
        exit();
            //exit(mysqli_error());
       }else{
        echo '<script>alert("Data Inserted Successfully.");</script>'
       }
    ?>

How to loop through an array containing objects and access their properties

This might help somebody. Maybe it's a bug in Node.

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

This doesn't work:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

But this works...

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

This works too...

while ((arr[c]) && (arr[c].name)) { c++; }

BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.

while ((arr[c].name) && (arr[c])) { c++; }

Error says the array is undefined, but it's not :-/ Node v11.15.0

Input button target="_blank" isn't causing the link to load in a new window/tab

<form target="_blank">
    <button class="btn btn-primary" formaction="http://www.google.com">Google</button>
</form>

How to "add existing frameworks" in Xcode 4?

Follow the screen shots

Go to linked framework and libraries

enter image description here

you are ready to Go!

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

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

Create a CSV File for a user in PHP

Instead of:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

Use:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

This works for both cached and dynamically loaded images.

function LoadImage(imgSrc, callback){
  var image = new Image();
  image.src = imgSrc;
  if (image.complete) {
    callback(image);
    image.onload=function(){};
  } else {
    image.onload = function() {
      callback(image);
      // clear onLoad, IE behaves erratically with animated gifs otherwise
      image.onload=function(){};
    }
    image.onerror = function() {
        alert("Could not load image.");
    }
  }
}

To use this script:

function AlertImageSize(image) {
  alert("Image size: " + image.width + "x" + image.height);
}
LoadImage("http://example.org/image.png", AlertImageSize);

Demo: http://jsfiddle.net/9543z/2/

How to serialize SqlAlchemy result to JSON?

Under Flask, this works and handles datatime fields, transforming a field of type
'time': datetime.datetime(2018, 3, 22, 15, 40) into
"time": "2018-03-22 15:40:00":

obj = {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}

# This to get the JSON body
return json.dumps(obj)

# Or this to get a response object
return jsonify(obj)

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

That's a tricky one... Your storage letter must be capical. For example "C:\..."

C++ Singleton design pattern

I did not find a CRTP implementation among the answers, so here it is:

template<typename HeirT>
class Singleton
{
public:
    Singleton() = delete;

    Singleton(const Singleton &) = delete;

    Singleton &operator=(const Singleton &) = delete;

    static HeirT &instance()
    {
        static HeirT instance;
        return instance;
    }
};

To use just inherit your class from this, like: class Test : public Singleton<Test>

Insert line at middle of file with Python?

There is a combination of techniques which I found useful in solving this issue:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    contents.insert(index, new_string)  # new_string should end in a newline
    fd.seek(0)  # readlines consumes the iterator, so we need to start over
    fd.writelines(contents)  # No need to truncate as we are increasing filesize

In our particular application, we wanted to add it after a certain string:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    if match_string in contents[-1]:  # Handle last line to prevent IndexError
        contents.append(insert_string)
    else:
        for index, line in enumerate(contents):
            if match_string in line and insert_string not in contents[index + 1]:
                contents.insert(index + 1, insert_string)
                break
    fd.seek(0)
    fd.writelines(contents)

If you want it to insert the string after every instance of the match, instead of just the first, remove the else: (and properly unindent) and the break.

Note also that the and insert_string not in contents[index + 1]: prevents it from adding more than one copy after the match_string, so it's safe to run repeatedly.

Timestamp to human readable format

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

Hex colors: Numeric representation for "transparent"?

Use following hexadecimal code for transparent text colour: #00FFFF00

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

Redirect to an external URL from controller action in Spring MVC

For me works fine:

@RequestMapping (value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI uri = new URI("http://www.google.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uri);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

Simple export and import of a SQLite database on Android

If you want this in kotlin . And perfectly working

 private fun exportDbFile() {

    try {

        //Existing DB Path
        val DB_PATH = "/data/packagename/databases/mydb.db"
        val DATA_DIRECTORY = Environment.getDataDirectory()
        val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)

        //COPY DB PATH
        val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
        val COPY_DB = "/mynewfolder/mydb.db"
        val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)

        File(COPY_DB_PATH.parent!!).mkdirs()
        val srcChannel = FileInputStream(INITIAL_DB_PATH).channel

        val dstChannel = FileOutputStream(COPY_DB_PATH).channel
        dstChannel.transferFrom(srcChannel,0,srcChannel.size())
        srcChannel.close()
        dstChannel.close()

    } catch (excep: Exception) {
        Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
        Log.e("FILECOPYERROR>>>>",excep.toString())
        excep.printStackTrace()
    }

}

SQL Server AS statement aliased column within WHERE statement

SQL doesn't typically allow you to reference column aliases in WHERE, GROUP BY or HAVING clauses. MySQL does support referencing column aliases in the GROUP BY and HAVING, but I stress that it will cause problems when porting such queries to other databases.

When in doubt, use the actual column name:

SELECT t.lat AS latitude 
  FROM poi_table t
 WHERE t.lat < 500

I added a table alias to make it easier to see what is an actual column vs alias.

Update


A computed column, like the one you see here:

SELECT *, 
       ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
  FROM poi_table 
 WHERE distance < 500;

...doesn't change that you can not reference a column alias in the WHERE clause. For that query to work, you'd have to use:

SELECT *, 
       ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
  FROM poi_table
 WHERE ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) < 500;

Be aware that using a function on a column (IE: RADIANS(lat)) will render an index useless, if one exists on the column.

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

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 c.id = x.id
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 c.id = x.id
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, c.id);

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], c.id);

How do I center a window onscreen in C#?

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

How do I find the width & height of a terminal window?

To do this in Windows CLI environment, the best way I can find is to use the mode command and parse the output.

function getTerminalSizeOnWindows() {
  $output = array();
  $size = array('width'=>0,'height'=>0);
  exec('mode',$output);
  foreach($output as $line) {
    $matches = array();
    $w = preg_match('/^\s*columns\:?\s*(\d+)\s*$/i',$line,$matches);
    if($w) {
      $size['width'] = intval($matches[1]);
    } else {
      $h = preg_match('/^\s*lines\:?\s*(\d+)\s*$/i',$line,$matches);
      if($h) {
        $size['height'] = intval($matches[1]);
      }
    }
    if($size['width'] AND $size['height']) {
      break;
    }
  }
  return $size;
}

I hope it's useful!

NOTE: The height returned is the number of lines in the buffer, it is not the number of lines that are visible within the window. Any better options out there?

How to read a single character at a time from a file in Python?

Just:

myfile = open(filename)
onecaracter = myfile.read(1)

Find full path of the Python interpreter?

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $ 

ArrayList of String Arrays

List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr  = new String[3];

addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";

addresses.add(addressesArr);

How do I revert an SVN commit?

It is impossible to "uncommit" a revision, but you can revert your working copy to version 1943 and commit that as version 1945. The versions 1943 and 1945 will be identical, effectively reverting the changes.

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

calculate the mean for each column of a matrix in R

In case you have NA's:

sapply(data, mean, na.rm = T)      # Returns a vector (with names)   
lapply(data, mean, na.rm = T)      # Returns a list  

Remember that "mean" needs numeric data. If you have mixed class data, then use:

numdata<-data[sapply(data, is.numeric)]  
sapply(numdata, mean, na.rm = T)  # Returns a vector
lapply(numdata, mean, na.rm = T)  # Returns a list  

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

pdftk compression option

If file size is still too large it could help using ps2pdf to downscale the resolution of the produced pdf file:

pdf2ps input.pdf tmp.ps
ps2pdf -dPDFSETTINGS=/screen -dDownsampleColorImages=true -dColorImageResolution=200 -dColorImageDownsampleType=/Bicubic tmp.ps output.pdf

Adjust the value of the -dColorImageResolution option to achieve a result that fits your needs (the value describes the image resolution in DPIs). If your input file is in grayscale, replacing Color through Gray or using both options in the above command could also help. Further fine-tuning is possible by changing the -dPDFSETTINGS option to /default or /printer. For explanations of the all possible options consult the ps2pdf manual.

How to convert all tables in database to one collation?

You can use this BASH script:

#!/bin/bash

USER="YOUR_DATABASE_USER"
PASSWORD="YOUR_USER_PASSWORD"
DB_NAME="DATABASE_NAME"
CHARACTER_SET="utf8" # your default character set
COLLATE="utf8_general_ci" # your default collation

tables=`mysql -u $USER -p$PASSWORD -e "SELECT tbl.TABLE_NAME FROM information_schema.TABLES tbl WHERE tbl.TABLE_SCHEMA = '$DB_NAME' AND tbl.TABLE_TYPE='BASE TABLE'"`

for tableName in $tables; do
    if [[ "$tableName" != "TABLE_NAME" ]] ; then
        mysql -u $USER -p$PASSWORD -e "ALTER TABLE $DB_NAME.$tableName DEFAULT CHARACTER SET $CHARACTER_SET COLLATE $COLLATE;"
        echo "$tableName - done"
    fi
done

jQuery append() vs appendChild()

I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.

yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first

var p = document.createElement('p')

then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element or a combination!

$('p').append('<span> I have been appended </span>');

What's a good IDE for Python on Mac OS X?

Pydev for Eclipse, as others have mentioned, is good.

Netbeans has a beta Python plugin that is a little rough around the edges, but could turn into something really cool.

Additionally there is a long list of programming centric text editors for the mac, that may or may not fit your needs.

  • Textmate - costs money, people love this program, but I haven't used it enough to see what all the fuss is about.
  • Jedit - Java based text editor, has some nice features, but the startup time isn't great (due to Java).
  • CarbonEmacs - Decent Emacs port.
  • AquaEmacs - Better Emacs port.
  • TextWrangler - Lite, free (as in beer) verision of BBEdit.
  • BBEdit - The old guard. The defacto editor before Textmate stole its limelight. Expensive.
  • Smultron - Very nice editor, the UI is similar to Textmate.
  • Idle - Python's own little editor, has some nice features, but also some major problems. I've personally found it too unstable for my usage.
  • Sublime Text - This is really sweet text editor that has some surprisingly good Python support.
  • Pycharm - Another solid full on IDE for Python.

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I normally use action="", which is XHTML valid and retains the GET data in the URL.

Find an element in DOM based on an attribute value

Here is an example , How to search images in a document by src attribute :

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_