Programs & Examples On #Geopy

geopy allows you to convert between partial place names and latitude/longitude coordinates by wrapping six different online API's and providing access through one standard interface.

Where do I find some good examples for DDD?

The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)

That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.

You haven't specified which language you're using, but I'll give you a few in a few different languages:

DDDSample - a Java sample that reflects the examples Eric Evans talks about in his book. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.

dddps - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#

S#arp Architecture - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.

With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.

JAXB Exception: Class not known to this context

I had the same exception on Tomcat.. I found another problem - when i use wsimport over maven plugin to generate stubs for more then 1 WSDLs - class ObjectFactory (stubs references to this class) contains methods ONLY for one wsdl. So you should merge all methods in one ObjectFactory class (for each WSDL) or generate each wsdl stubs in different directories (there will be separates ObjectFactory classes). It solves problem for me with this exception..J

Save results to csv file with Python

This is how I do it

 import csv
    file = open('???.csv', 'r')
    read = csv.reader(file)
    for column in read:
            file = open('???.csv', 'r')
            read = csv.reader(file)
            file.close()
            file = open('????.csv', 'a', newline='')
            write = csv.writer(file, delimiter = ",")
            write.writerow((, ))
            file.close()

What is the difference between resource and endpoint?

Possibly mine isn't a great answer but here goes.

Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.

To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.

So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.

Edit

I blogged about this.

https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819

Which is the preferred way to concatenate a string in Python?

The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:

a = a + b:
0.11338996887207031
a += b:
0.11040496826171875

However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:

a += b:
0.10780501365661621
a.append(b):
0.1123361587524414

OK, turns out that even when the resulting string is a million characters long, appending was still faster.

Now let's try with appending a thousand character long string a hundred thousand times:

a += b:
0.41823482513427734
a.append(b):
0.010656118392944336

The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much faster. That that timing doesn't include the final a.join(). So how long would that take?

a.join(a):
0.43739795684814453

Oups. Turns out even in this case, append/join is slower.

So where does this recommendation come from? Python 2?

a += b:
0.165287017822
a.append(b):
0.0132720470428
a.join(a):
0.114929914474

Well, append/join is marginally faster there if you are using extremely long strings (which you usually aren't, what would you have a string that's 100MB in memory?)

But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons.

Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore (or at least Python 2.4.7), so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-)

(Update: Turns out when I did the testing more carefully that using + and += is faster for two strings on Python 2.3 as well. The recommendation to use ''.join() must be a misunderstanding)

However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it.

Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else.

So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines.

Python - Module Not Found

You need to make sure the module is installed for all versions of python

You can check to see if a module is installed for python by running:

pip uninstall moduleName

If it is installed, it will ask you if you want to delete it or not. My issue was that it was installed for python, but not for python3. To check to see if a module is installed for python3, run:

python3 -m pip uninstall moduleName

After doing this, if you find that a module is not installed for one or both versions, use these two commands to install the module.

  • pip install moduleName
  • python3 -m pip install moduleName

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

Everything is fine, just one mistake is there. Change this:

$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);
$query = mysql_query("SELECT Count(*) FROM Users WHERE username=$username, $con");

if (mysql_num_rows($query) != 0)
{
    echo "Username already exists";
}
else
{
  ...
}

SELECT * will not work, use with SELECT COUNT(*).

Dynamically create Bootstrap alerts box through JavaScript

I found that AlertifyJS is a better alternative and have a Bootstrap theme.

alertify.alert('Alert Title', 'Alert Message!', function(){ alertify.success('Ok'); });

Also have a 4 components: Alert, Confirm, Prompt and Notifier.

Exmaple: JSFiddle

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Checking for empty queryset in Django

if not orgs:
    # Do this...
else:
    # Do that...

Reading a UTF8 CSV file with Python

Worth noting that if nothing worked for you, you may have forgotten to escape your path.
For example, this code:

f = open("C:\Some\Path\To\file.csv")

Would result in an error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

To fix, simply do:

f = open("C:\\Some\\Path\\To\\file.csv")

C compiler for Windows?

I'm late to this party, but for any future C folks on Windows, Visual Studio targets C90 instead of C99, which is what you'd get on *nix. I am currently targeting C99 on Windows by using Sublime Text 2 in tandem with Cygwin.

Get exit code of a background process

This may be extending beyond your question, however if you're concerned about the length of time processes are running for, you may be interested in checking the status of running background processes after an interval of time. It's easy enough to check which child PIDs are still running using pgrep -P $$, however I came up with the following solution to check the exit status of those PIDs that have already expired:

cmd1() { sleep 5; exit 24; }
cmd2() { sleep 10; exit 0; }

pids=()
cmd1 & pids+=("$!")
cmd2 & pids+=("$!")

lasttimeout=0
for timeout in 2 7 11; do
  echo -n "interval-$timeout: "
  sleep $((timeout-lasttimeout))

  # you can only wait on a pid once
  remainingpids=()
  for pid in ${pids[*]}; do
     if ! ps -p $pid >/dev/null ; then
        wait $pid
        echo -n "pid-$pid:exited($?); "
     else
        echo -n "pid-$pid:running; "
        remainingpids+=("$pid")
     fi
  done
  pids=( ${remainingpids[*]} )

  lasttimeout=$timeout
  echo
done

which outputs:

interval-2: pid-28083:running; pid-28084:running; 
interval-7: pid-28083:exited(24); pid-28084:running; 
interval-11: pid-28084:exited(0); 

Note: You could change $pids to a string variable rather than array to simplify things if you like.

Struct like objects in Java

Do not use public fields

Don't use public fields when you really want to wrap the internal behavior of a class. Take java.io.BufferedReader for example. It has the following field:

private boolean skipLF = false; // If the next character is a line feed, skip it

skipLF is read and written in all read methods. What if an external class running in a separate thread maliciously modified the state of skipLF in the middle of a read? BufferedReader will definitely go haywire.

Do use public fields

Take this Point class for example:

class Point {
    private double x;
    private double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return this.x;
    }

    public double getY() {
        return this.y;
    }

    public void setX(double x) {
        this.x = x;
    }

    public void setY(double y) {
        this.y = y;
    }
}

This would make calculating the distance between two points very painful to write.

Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));

The class does not have any behavior other than plain getters and setters. It is acceptable to use public fields when the class represents just a data structure, and does not have, and never will have behavior (thin getters and setters is not considered behavior here). It can be written better this way:

class Point {
    public double x;
    public double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));

Clean!

But remember: Not only your class must be absent of behavior, but it should also have no reason to have behavior in the future as well.


(This is exactly what this answer describes. To quote "Code Conventions for the Java Programming Language: 10. Programming Practices":

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

So the official documentation also accepts this practice.)


Also, if you're extra sure that members of above Point class should be immutable, then you could add final keyword to enforce it:

public final double x;
public final double y;

Java ArrayList of Arrays?

ArrayList<String[]> action = new ArrayList<String[]>();

Don't need String[2];

Compare given date with today

Here you go:

function isToday($time) // midnight second
{
    return (strtotime($time) === strtotime('today'));
}

isToday('2010-01-22 00:00:00.0'); // true

Also, some more helper functions:

function isPast($time)
{
    return (strtotime($time) < time());
}

function isFuture($time)
{
    return (strtotime($time) > time());
}

How to enumerate an enum

If you have:

enum Suit
{
   Spades,
   Hearts,
   Clubs,
   Diamonds
}

This:

foreach (var e in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(e.ToString() + " = " + (int)e);
}

Will output:

Spades = 0
Hearts = 1
Clubs = 2
Diamonds = 3

Get second child using jQuery

You can use two methods in jQuery as given below-

Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element.

_x000D_
_x000D_
$( "ul li:nth-child(2)" ).click(function(){_x000D_
  //do something_x000D_
});
_x000D_
_x000D_
_x000D_

Using jQuery :eq() Selector

If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0. To select the 2nd element of li, you have to use 2 as the argument.

_x000D_
_x000D_
$( "ul li:eq(1)" ).click(function(){_x000D_
  //do something_x000D_
});
_x000D_
_x000D_
_x000D_

See Example: Get Second Child Element of List in jQuery

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

ArrayList of String Arrays

Following works in Java 8..

List<String[]> addresses = new ArrayList<>();

Styling HTML5 input type number

Unfortunately in HTML 5 the 'pattern' attribute is linked to only 4-5 attributes. However if you are willing to use a "text" field instead and convert to number later, this might help you;

This limits an input from 1 character (numberic) to 3.

<input name=quantity type=text pattern='[0-9]{1,3}'>

The CSS basically allows for confirmation with an "Thumbs up" or "Down".

Example 1

Example 2

How to save user input into a variable in html and js

First, make your markup more portable/reusable. I also set the button's type to 'button' instead of using the onsubmit attribute. You can toggle the type attribute to submit if the form needs to interact with a server.

<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
    <label id='nameLable' for='nameField'>Create a username:</label>
    <input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
    <button id='subButton' type='button'>Print your name!</button>
</div>
</form>

<div>
    <p id='result'></p></div>
</div>

Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. You can change this to whatever constant you want.

function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');

if (nameField.length < 3) {
    result.textContent = 'Username must contain at least 3 characters';
    //alert('Username must contain at least 3 characters');
} else {
    result.textContent = 'Your username is: ' + nameField;
    //alert(nameField);
}
}

Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.

var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false); 

Here is a working and lightly styled demo:

CodePen demo of this answer.

Bootstrap 3: How do you align column content to bottom of row

I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)

I found another working solution :

.bottom-column 
{
   display: inline-block;
   vertical-align: middle;
   float: none;
}

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

How do I assert equality on two classes without an equals method?

You can override the equals method of the class like:

@Override
public int hashCode() {
    int hash = 0;
    hash += (app != null ? app.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    HubRule other = (HubRule) object;

    if (this.app.equals(other.app)) {
        boolean operatorHubList = false;

        if (other.operator != null ? this.operator != null ? this.operator
                .equals(other.operator) : false : true) {
            operatorHubList = true;
        }

        if (operatorHubList) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Well, if you want to compare two object from a class you must implement in some way the equals and the hash code method

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

How to get current SIM card number in Android?

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

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

Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for whatsapp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.

What is the difference between Step Into and Step Over in a debugger

You can't go through the details of the method by using the step over. If you want to skip the current line, you can use step over, then you only need to press the F6 for only once to move to the next line. And if you think there's someting wrong within the method, use F5 to examine the details.

Debugging JavaScript in IE7

Running your code through a Javascript static analysis tool like JSLint can catch some common IE7 errors, such as trailing commas in object definitions.

C# 4.0 optional out/ref arguments

void foo(ref int? n)
{
    return null;
}

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Setting environment variables in Linux using Bash

Set a local and environment variable using Bash on Linux

Check for a local or environment variables for a variable called LOL in Bash:

el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $

Sanity check, no local or environment variable called LOL.

Set a local variable called LOL in local, but not environment. So set it:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $

Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash.

Set a local variable, and then clear out all local variables in Bash

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $

You could also just unset the one variable:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $

Local variable LOL is gone.

Promote a local variable to an environment variable:

el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable

Note that exporting makes it show up as both a local variable and an environment variable.

Exported variable DOGE above survives a Bash reset:

el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'

Unset all environment variables:

You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:

el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN

You created an environment variable, and then reset the terminal to get rid of them.

Or you could set and unset an environment variable manually like this:

el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $

Generating random strings with T-SQL

In SQL Server 2012+ we could concatenate the binaries of some (G)UIDs and then do a base64 conversion on the result.

SELECT 
    textLen.textLen
,   left((
        select  CAST(newid() as varbinary(max)) + CAST(newid() as varbinary(max)) 
        where   textLen.textLen is not null /*force evaluation for each outer query row*/ 
        FOR XML PATH(''), BINARY BASE64
    ),textLen.textLen)   as  randomText
FROM ( values (2),(4),(48) ) as textLen(textLen)    --define lengths here
;

If you need longer strings (or you see = characters in the result) you need to add more + CAST(newid() as varbinary(max)) in the sub select.

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Maven Modules + Building a Single Specific Module

Maven absolutely was designed for this type of dependency.

mvn package won't install anything in your local repository it just packages the project and leaves it in the target folder.

Do mvn install in parent project (A), with this all the sub-modules will be installed in your computer's Maven repository, if there are no changes you just need to compile/package the sub-module (B) and Maven will take the already packaged and installed dependencies just right.

You just need to a mvn install in the parent project if you updated some portion of the code.

Laravel Redirect Back with() Message

For Laravel 3

Just a heads up on @giannis christofakis answer; for anyone using Laravel 3 replace

return Redirect::back()->withErrors(['msg', 'The Message']);

with:

return Redirect::back()->with_errors(['msg', 'The Message']);

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

Angular 2 Hover event

You can do it with a host:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'blue';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

   private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )

How do I drop table variables in SQL-Server? Should I even do this?

Table variables are just like int or varchar variables.

You don't need to drop them. They have the same scope rules as int or varchar variables

The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

Failed to execute 'createObjectURL' on 'URL':

Video with fall back:

try {
  video.srcObject = mediaSource;
} catch (error) {
  video.src = URL.createObjectURL(mediaSource);
}
video.play();

From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-

  1. Object Constructor
  2. Literal constructor
  3. Function Based
  4. Protoype Based
  5. Function and Prototype Based
  6. Singleton Based

Examples:

  1. Object constructor
var person = new Object();

person.name = "Anand",
person.getName = function(){
  return this.name ; 
};
  1. Literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name
  } 
} 
  1. function Constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
} 
  1. Prototype
function Person(){};

Person.prototype.name = "Anand";
  1. Function/Prototype combination
function Person(name){
  this.name = name;
} 
Person.prototype.getName = function(){
  return this.name
} 
  1. Singleton
var person = new function(){
  this.name = "Anand"
} 

You can try it on console, if you have any confusion.

Difference between web server, web container and application server

The basic idea of Servlet container is using Java to dynamically generate the web page on the server side using Servlets and JSP. So servlet container is essentially a part of a web server that interacts with the servlets.

angularjs directive call function specified in attribute and pass an argument to it

My solution:

  1. on polymer raise an event (eg. complete)
  2. define a directive linking the event to control function

Directive

/*global define */
define(['angular', './my-module'], function(angular, directives) {
    'use strict';
    directives.directive('polimerBinding', ['$compile', function($compile) {

            return {
                 restrict: 'A',
                scope: { 
                    method:'&polimerBinding'
                },
                link : function(scope, element, attrs) {
                    var el = element[0];
                    var expressionHandler = scope.method();
                    var siemEvent = attrs['polimerEvent'];
                    if (!siemEvent) {
                        siemEvent = 'complete';
                    }
                    el.addEventListener(siemEvent, function (e, options) {
                        expressionHandler(e.detail);
                    })
                }
            };
        }]);
});

Polymer component

<dom-module id="search">

<template>
<h3>Search</h3>
<div class="input-group">

    <textarea placeholder="search by expression (eg. temperature>100)"
        rows="10" cols="100" value="{{text::input}}"></textarea>
    <p>
        <button id="button" class="btn input-group__addon">Search</button>
    </p>
</div>
</template>

 <script>
  Polymer({
    is: 'search',
            properties: {
      text: {
        type: String,
        notify: true
      },

    },
    regularSearch: function(e) {
      console.log(this.range);
      this.fire('complete', {'text': this.text});
    },
    listeners: {
        'button.click': 'regularSearch',
    }
  });
</script>

</dom-module>

Page

 <search id="search" polimer-binding="searchData"
 siem-event="complete" range="{{range}}"></siem-search>

searchData is the control function

$scope.searchData = function(searchObject) {
                    alert('searchData '+ searchObject.text + ' ' + searchObject.range);

}

What is The Rule of Three?

Many of the existing answers already touch the copy constructor, assignment operator and destructor. However, in post C++11, the introduction of move semantic may expand this beyond 3.

Recently Michael Claisse gave a talk that touches this topic: http://channel9.msdn.com/events/CPP/C-PP-Con-2014/The-Canonical-Class

Remove ALL white spaces from text

Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:

_x000D_
_x000D_
const text = ' a b    c d e   f g   ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
_x000D_
_x000D_

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Convert dictionary to list collection in C#

foreach (var item in dicNumber)
{
    listnumber.Add(item.Key);
}

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

I found another way which prevents any conflicting merge on cherry-picking which IMO is kind of easy to remember and understand. Since you are actually not cherry-picking a commit, but part of it, you need to split it first and then create a commit which will suit your needs and cherry-pick it.

First create a branch from the commit you want to split and checkout it:

$ git checkout COMMIT-TO-SPLIT-SHA -b temp

Then revert previous commit:

$ git reset HEAD~1

Then add the files/changes you want to cherry-pick:

$ git add FILE

and commit it:

$ git commit -m "pick me"

note the commit hash, let's call it PICK-SHA and go back to your main branch, master for example forcing the checkout:

$ git checkout -f master

and cherry-pick the commit:

$ git cherry-pick PICK-SHA

now you can delete the temp branch:

$ git branch -d temp -f

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

Powershell 2 copy-item which creates a folder if doesn't exist

  $filelist | % {
    $file = $_
    mkdir -force (Split-Path $dest) | Out-Null
    cp $file $dest
  } 

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

How to activate an Anaconda environment

All the former answers seem to be outdated.

conda activate was introduced in conda 4.4 and 4.6.

conda activate: The logic and mechanisms underlying environment activation have been reworked. With conda 4.4, conda activate and conda deactivate are now the preferred commands for activating and deactivating environments. You’ll find they are much more snappy than the source activate and source deactivate commands from previous conda versions. The conda activate command also has advantages of (1) being universal across all OSes, shells, and platforms, and (2) not having path collisions with scripts from other packages like python virtualenv’s activate script.

Examples

conda create -n venv-name python=3.6
conda activate -n venv-name
conda deactivate

These new sub-commands are available in "Aanconda Prompt" and "Anaconda Powershell Prompt" automatically. To use conda activate in every shell (normal cmd.exe and powershell), check expose conda command in every shell on Windows.

References

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

The API return value in my case as shown here:

{
  "pageIndex": 1,
  "pageSize": 10,
  "totalCount": 1,
  "totalPageCount": 1,
  "items": [
    {
      "firstName": "Stephen",
      "otherNames": "Ebichondo",
      "phoneNumber": "+254721250736",
      "gender": 0,
      "clientStatus": 0,
      "dateOfBirth": "1979-08-16T00:00:00",
      "nationalID": "21734397",
      "emailAddress": "[email protected]",
      "id": 1,
      "addedDate": "2018-02-02T00:00:00",
      "modifiedDate": "2018-02-02T00:00:00"
    }
  ],
  "hasPreviousPage": false,
  "hasNextPage": false
}

The conversion of the items array to list of clients was handled as shown here:

 if (responseMessage.IsSuccessStatusCode)
        {
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            JObject result = JObject.Parse(responseData);

            var clientarray = result["items"].Value<JArray>();
            List<Client> clients = clientarray.ToObject<List<Client>>();
            return View(clients);
        }

req.body empty on posts

A similar problem happened to me, I simply mixed the order of the callback params. Make sure your are setting up the callback functions in the correct order. At least for anyone having the same problem.

router.post('/', function(req, res){});

How to append binary data to a buffer in node.js

Updated Answer for Node.js ~>0.8

Node is able to concatenate buffers on its own now.

var newBuffer = Buffer.concat([buffer1, buffer2]);

Old Answer for Node.js ~0.6

I use a module to add a .concat function, among others:

https://github.com/coolaj86/node-bufferjs

I know it isn't a "pure" solution, but it works very well for my purposes.

Viewing full version tree in git

If you don't need branch or tag name:
git log --oneline --graph --all --no-decorate

If you don't even need color (to avoid tty color sequence):
git log --oneline --graph --all --no-decorate --no-color

And a handy alias (in .gitconfig) to make life easier:

[alias]
  tree = log --oneline --graph --all --no-decorate

Only last option takes effect, so it's even possible to override your alias:
git tree --decorate

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

How do I undo the most recent local commits in Git?

Use git revert <commit-id>.

To get the commit ID, just use git log.

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Eclipse Error: "Failed to connect to remote VM"

Remove your proxy from eclipse!

Go to network Connections within General Preferences ( Windows -> Preferences ) and set "Active Provider" to "Direct"

remove proxy

Reboot your Eclipse after that

Facebook Oauth Logout

the mobile solution suggested by Sumit works perfectly for AS3 Air:

html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"

Format in kotlin string templates

It's simple, use:

val str: String = "%.2f".format(3.14159)

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

push multiple elements to array

Pushing multiple objects at once often depends on how are you declaring your array.

This is how I did

//declaration
productList= [] as  any;

now push records

this.productList.push(obj.lenght, obj2.lenght, items);

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Opening A Specific File With A Batch File?

If you are trying to open a file in the same directory it would be:

./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)

Or, if trying to backtrack from the same directory it would be:

../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)

Else, if you need a straight one from start, it would be:

(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/)

activity_main.xml:

<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>

<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>

</ListView>
</RelativeLayout>

MainActivity.java:

package com.pdffilefromsdcard;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

}

private void init() {

lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);

Log.e(“Position”, i + “”);
}
});
}

public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {

if (listFile[i].isDirectory()) {
getfile(listFile[i]);

} else {

boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {

for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {

}
}

if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);

}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);

}
} else {
boolean_permission = true;

getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

boolean_permission = true;
getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();

}
}
}

}

activity_pdf.xml:

<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>

<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_margin=”10dp”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>

PdfActivity.java:

package com.pdffilefromsdcard;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.io.File;
import java.util.List;

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {

PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}

private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}

private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();

pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)

.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);

}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {

Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));

if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

Thanks!

Check if a number is odd or even in python

It shouldn't matter if the word has an even or odd amount fo letters:

def is_palindrome(word):
    if word == word[::-1]:
        return True
    else:
        return False

Limiting double to 3 decimal places

I can't think of a reason to explicitly lose precision outside of display purposes. In that case, simply use string formatting.

double example = 12.34567;

Console.Out.WriteLine(example.ToString("#.000"));

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Print array elements on separate lines in Bash?

Just quote the argument to echo:

( IFS=$'\n'; echo "${my_array[*]}" )

the sub shell helps restoring the IFS after use

How to git commit a single file/directory

you try if You are in Master branch git commit -m "Commit message" -- filename.ext

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

How to Get Element By Class in JavaScript?

A Simple and an easy way

var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
    var item = cusid_ele[i];  
    item.innerHTML = 'this is value';
}

use jQuery to get values of selected checkboxes

So all in one line:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"] , it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.

How can I drop a table if there is a foreign key constraint in SQL Server?

BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change

DECLARE @cmd varchar(4000)

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 

select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @cmd
WHILE @@FETCH_STATUS = 0
BEGIN
    -- EXEC (@cmd)
    PRINT @cmd
    FETCH NEXT FROM MY_CURSOR INTO @cmd
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

GO

Construct pandas DataFrame from list of tuples of (row,col,values)

This is what I expected to see when I came to this question:

#!/usr/bin/env python

import pandas as pd


df = pd.DataFrame([(1, 2, 3, 4),
                   (5, 6, 7, 8),
                   (9, 0, 1, 2),
                   (3, 4, 5, 6)],
                  columns=list('abcd'),
                  index=['India', 'France', 'England', 'Germany'])
print(df)

gives

         a  b  c  d
India    1  2  3  4
France   5  6  7  8
England  9  0  1  2
Germany  3  4  5  6

How to plot multiple functions on the same figure, in Matplotlib?

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

How can I make a checkbox readonly? not disabled?

I personally like to do it this way:

<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">

I think this is better for two reasons:

  1. User clearly understand that he can't edit this value
  2. The value is sent when submitting the form.

javac: invalid target release: 1.8

For IntelliJ IDEA Ultimate latest version as of 18th Dec 2017, if the above suggestions don't work, then please try the following: Right Click on the project and navigate to "Open Module Settings". Open it, then change the "Language Level" from the dropdown.

Remove part of string in Java

String Replace

String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");

Edit:

By Index

s = s.substring(0, s.indexOf("(") - 1);

Python Pandas - Missing required dependencies ['numpy'] 1

I had to install this other package:

sudo apt-get install libatlas-base-dev

Seems like it is a dependency for numpy but the pip or apt-get don't install it automatically for whatever reason.

Maximum execution time in phpMyadmin

Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:

C:\xampp\apache\bin\php.ini

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Maven: add a folder or jar file into current classpath

From docs and example it is not clear that classpath manipulation is not allowed.

<configuration>
 <compilerArgs>
  <arg>classpath=${basedir}/lib/bad.jar</arg>
 </compilerArgs>
</configuration>

But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)

-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.

Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?

    <properties>
      <cpfile>cp.txt</cpfile>
    </properties>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.9</version>
    <executions>
      <execution>
        <id>build-classpath</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>build-classpath</goal>
        </goals>
        <configuration>
          <outputFile>${cpfile}</outputFile>
        </configuration>
      </execution>
    </executions>
  </plugin>

Read file (Read a file into a Maven property)

<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          def file = new File(project.properties.cpfile)
          project.properties.cp = file.getText()
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

and finally

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <compilerArgs>
         <arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
      </compilerArgs>
    </configuration>
   </plugin>

How do you performance test JavaScript code?

This is a good way of collecting performance information for the specific operation.

start = new Date().getTime(); 
for (var n = 0; n < maxCount; n++) {
/* perform the operation to be measured *//
}
elapsed = new Date().getTime() - start;
assert(true,"Measured time: " + elapsed);

GUI Tool for PostgreSQL

There is a comprehensive list of tools on the PostgreSQL Wiki:

https://wiki.postgresql.org/wiki/PostgreSQL_Clients

And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.

How to override and extend basic Django admin templates?

The best way to do it is to put the Django admin templates inside your project. So your templates would be in templates/admin while the stock Django admin templates would be in say template/django_admin. Then, you can do something like the following:

templates/admin/change_form.html

{% extends 'django_admin/change_form.html' %}

Your stuff here

If you're worried about keeping the stock templates up to date, you can include them with svn externals or similar.

How to set initial value and auto increment in MySQL?

Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.

Now, Set your values and then press Go under the Table Options Box.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

You can find and kill the running processes: ps aux | grep puma Then you can kill it with kill PID

Using Get-childitem to get a list of files modified in the last 3 days

Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:

$compareDate = (Get-Date).AddDays(-3)    
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count

Angular HTML binding

Just to post a little addition to all the great answers so far: If you are using [innerHTML] to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.

With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer just like [innerHTML] does as well, but retains the ability to load components (in a safe manner).

See it in action in this Stackblitz.

How to recursively delete an entire directory with PowerShell 2.0?

To delete the complete contents including the folder structure use

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

The -recurse added to remove-item ensures interactive prompts are disabled.

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Is there a MySQL option/feature to track history of changes to records?

Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.

A good python library called noplay can be used. More info here.

How to use PHP's password_hash to hash and verify passwords

Yes, it's true. Why do you doubt the php faq on the function? :)

The result of running password_hash() has has four parts:

  1. the algorithm used
  2. parameters
  3. salt
  4. actual password hash

So as you can see, the hash is a part of it.

Sure, you could have an additional salt for an added layer of security, but I honestly think that's overkill in a regular php application. The default bcrypt algorithm is good, and the optional blowfish one is arguably even better.

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

How to define static property in TypeScript interface

You can merge interface with namespace using the same name:

interface myInterface { }

namespace myInterface {
  Name:string;
}

But this interface is only useful to know that its have property Name. You can not implement it.

Monad in plain English? (For the OOP programmer with no FP background)

From wikipedia:

In functional programming, a monad is a kind of abstract data type used to represent computations (instead of data in the domain model). Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations,1[2] or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).

Formally, a monad is constructed by defining two operations (bind and return) and a type constructor M that must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments). The return operation takes a value from a plain type and puts it into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.

A programmer will compose monadic functions to define a data-processing pipeline. The monad acts as a framework, as it's a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.[3] The bind and return operators interleaved in the pipeline will be executed after each monadic function returns control, and will take care of the particular aspects handled by the monad.

I believe it explains it very well.

How do I generate a random number between two variables that I have stored?

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

Bootstrap carousel resizing image

Had the same problem and none of the CSS solutions presented here worked.

What worked for me was setting up a height="360" without setting any width. My photos aren't the same size and like this they have room to adjust their with but keep the height fixed.

Limit Decimal Places in Android EditText

I have modified the above solutions and created following one. You can set number of digits before and after decimal point.

public class DecimalDigitsInputFilter implements InputFilter {

private final Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    mPattern = Pattern.compile(String.format("[0-9]{0,%d}(\\.[0-9]{0,%d})?", digitsBeforeZero, digitsAfterZero));
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    Matcher matcher = mPattern.matcher(createResultString(source, start, end, dest, dstart, dend));
    if (!matcher.matches())
        return "";
    return null;
}

private String createResultString(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    String sourceString = source.toString();
    String destString = dest.toString();
    return destString.substring(0, dstart) + sourceString.substring(start, end) + destString.substring(dend);
}

}

Best way to reverse a string

"Better way" depends on what is more important to you in your situation, performance, elegance, maintainability etc.

Anyway, here's an approach using Array.Reverse:

string inputString="The quick brown fox jumps over the lazy dog.";
char[] charArray = inputString.ToCharArray(); 
Array.Reverse(charArray); 

string reversed = new string(charArray);

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

Django -- Template tag in {% if %} block

Sorry for comment in an old post but if you want to use an else if statement this will help you

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}

For more info see Django Documentation

Fixing Segmentation faults in C++

  1. Compile your application with -g, then you'll have debug symbols in the binary file.

  2. Use gdb to open the gdb console.

  3. Use file and pass it your application's binary file in the console.

  4. Use run and pass in any arguments your application needs to start.

  5. Do something to cause a Segmentation Fault.

  6. Type bt in the gdb console to get a stack trace of the Segmentation Fault.

Removing a list of characters in string

i think this is simple enough and will do!

list = [",",",","!",";",":"] #the list goes on.....

theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
    if theString[i] in list:
        newString += "" #concatenate an empty string.
    else:
        newString += theString[i]

this is one way to do it. But if you are tired of keeping a list of characters that you want to remove, you can actually do it by using the order number of the strings you iterate through. the order number is the ascii value of that character. the ascii number for 0 as a char is 48 and the ascii number for lower case z is 122 so:

theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
     if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
         newString += ""
     else:
        newString += theString[i]

Extracting text from HTML file using Python

you can extract only text from HTML with BeautifulSoup

url = "https://www.geeksforgeeks.org/extracting-email-addresses-using-regular-expressions-python/"
con = urlopen(url).read()
soup = BeautifulSoup(con,'html.parser')
texts = soup.get_text()
print(texts)

How do I do top 1 in Oracle?

If you want just a first selected row, you can:

select fname from MyTbl where rownum = 1

You can also use analytic functions to order and take the top x:

select max(fname) over (rank() order by some_factor) from MyTbl

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

copy db file with adb pull results in 'permission denied' error

I had the same problem. My work around is to use adb shell and su. Next, copy the file to /sdcard/Download

Then, I can use adb pull to get the file.

best way to create object

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.

But for readability/maintainability reasons, avoid creating constructors with too many parameters.

In this case, both will do.

multi line comment vb.net in Visual studio 2010

The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C

Failed to start mongod.service: Unit mongod.service not found

You can repair

$ sudo rm /var/lib/mongodb/mongod.lock
$ mongod --repair
$ sudo service mongodb start

For Stop

$ sudo service mongodb stop

For Restart-

$ sudo service mongodb restart

For Status-

$ sudo service mongodb status

Can't escape the backslash with regex?

This solution fixed my problem while replacing br tag to '\n' .

alert(content.replace(/<br\/\>/g,'\n'));

Datatables - Search Box outside datatable

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

What determines the monitor my app runs on?

So I had this issue with Adobe Reader 9.0. Somehow the program forgot to open on my right monitor and was consistently opening on my left monitor. Most programs allow you to drag it over, maximize the screen, and then close it out and it will remember. Well, with Adobe, I had to drag it over and then close it before maximizing it, in order for Windows to remember which screen to open it in next time. Once you set it to the correct monitor, then you can maximize it. I think this is stupid, since almost all windows programs remember it automatically without try to rig a way for XP to remember.

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

Maven Java EE Configuration Marker with Java Server Faces 1.2

This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer

What exactly is Apache Camel?

Here is another attempt at it.

You know how there are/were things like Webmethods, ICAN Seebeyond, Tibco BW, IBM Broker. They all did help with integration solutions in the enterprise. These tools are commonly known by the name Enterprise Application Integration (EAI) tools.

There were mostly drag drop tools built around these technologies and in parts you would have to write adapters in Java. These adapter code were either untested or had poor tooling/automation around testing.

Just like with design patterns in programming, you have Enterprise Integration patterns for common integration solutions. They were made famous by a book of the same name by Gregor Hohpe and Bobby Woolf.

Although it is quite possible to implement integration solutions which use one or many EIP, Camel is an attempt at doing this within your code base using one of XML, Java, Groovy or Scala.

Camel supports all Enterprise Integration Patterns listed in the book via its rich DSL and routing mechanism.

So Camel is a competing technoloy to other EAI tools with better support for testing your integration code. The code is concise because of the Domain Specific Languages (DSLs). It is readable by even business users and it is free and makes you productive.

How to compare two tables column by column in oracle

SELECT *
  FROM (SELECT   table_name, COUNT (*) cnt
            FROM all_tab_columns
           WHERE owner IN ('OWNER_A')
        GROUP BY table_name) x,
       (SELECT   table_name, COUNT (*) cnt
            FROM all_tab_columns
           WHERE owner IN ('OWNER_B')
        GROUP BY table_name) y
 WHERE x.table_name = y.table_name AND x.cnt <> y.cnt;

CSS Font "Helvetica Neue"

Most windows users won't have that font on their computers. Also, you can't just submit it to your server and call it using font-face because this isn't a free font...

And last, but not least, answering the question that nobody mentioned yet, Helvetica and Helvetica Neue do not render well on screen unless they have a really big font-size. You'll find a lot of pages using this font, and in all of them you'll see that the top border of a line of text looks wavy and that some letters look taller than others. In my opinion this is the main reason why you shouldn't use it. There are other options for you to use, like Open Sans.

jQuery validate: How to add a rule for regular expression validation?

we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.

<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />

therefore we use the following snippet

$.validator.addMethod(
        "regex",
        function(value, element, regstring) {
            // fast exit on empty optional
            if (this.optional(element)) {
                return true;
            }

            var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
            if (regParts) {
                // the parsed pattern had delimiters and modifiers. handle them. 
                var regexp = new RegExp(regParts[1], regParts[2]);
            } else {
                // we got pattern string without delimiters
                var regexp = new RegExp(regstring);
            }

            return regexp.test(value);
        },
        "Please check your input."
);  

Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).

PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Find a class somewhere inside dozens of JAR files?

To search all jar files in a given directory for a particular class, you can do this:

ls *.jar | xargs grep -F MyClass

or, even simpler,

grep -F MyClass *.jar

Output looks like this:

Binary file foo.jar matches

It's very fast because the -F option means search for Fixed string, so it doesn't load the the regex engine for each grep invocation. If you need to, you can always omit the -F option and use regexes.

How to select the last record from MySQL table using SQL syntax

SELECT * 
FROM table_name
ORDER BY id DESC
LIMIT 1

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

How do I set the proxy to be used by the JVM

You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).

Send Email Intent

Finally come up with best way to do

String to = "[email protected]";
String subject= "Hi I am subject";
String body="Hi I am test body";
String mailTo = "mailto:" + to +
        "?&subject=" + Uri.encode(subject) +
        "&body=" + Uri.encode(body);
Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setData(Uri.parse(mailTo));
startActivity(emailIntent);

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

Have answered it already in https://stackoverflow.com/a/53491151/1909708.

This fails because neither the certificate common name (CN in certification Subject) nor any of the alternate names (Subject Alternative Name in the certificate) match with the target hostname or IP adress.

For e.g., from a JVM, when trying to connect to an IP address (WW.XX.YY.ZZ) and not the DNS name (https://stackoverflow.com), the HTTPS connection will fail because the certificate stored in the java truststore cacerts expects common name (or certificate alternate name like stackexchange.com or *.stackoverflow.com etc.) to match the target address.

Please check: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#HostnameVerifier

    HttpsURLConnection urlConnection = (HttpsURLConnection) new URL("https://WW.XX.YY.ZZ/api/verify").openConnection();
    urlConnection.setSSLSocketFactory(socketFactory());
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.setUseCaches(false);
    urlConnection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    });
    urlConnection.getOutputStream();

Above, passed an implemented HostnameVerifier object which is always returns true:

new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    }

Detect click outside Angular component

An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.

http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview

_x000D_
_x000D_
  private wasInside = false;_x000D_
  _x000D_
  @HostListener('click')_x000D_
  clickInside() {_x000D_
    this.text = "clicked inside";_x000D_
    this.wasInside = true;_x000D_
  }_x000D_
  _x000D_
  @HostListener('document:click')_x000D_
  clickout() {_x000D_
    if (!this.wasInside) {_x000D_
      this.text = "clicked outside";_x000D_
    }_x000D_
    this.wasInside = false;_x000D_
  }
_x000D_
_x000D_
_x000D_

Get the new record primary key ID from MySQL insert query?

If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.

Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();

CSS opacity only to background color, not the text on it?

I had the same problem. I want a 100% transparent background color. Just use this code; it's worked great for me:

rgba(54, 25, 25, .00004);

You can see examples on the left side on this web page (the contact form area).

Unable to create Android Virtual Device

This can happen when:

  • You have multiple copies of the Android SDK installed on your machine. You may be updating the available images and devices for one copy of the Android SDK, and trying to debug or run your application in another.

    If you're using Eclipse, take a look at your "Preferences | Android | SDK Location". Make sure it's the path you expect. If not, change the path to point to where you think the Android SDK is installed.

  • You don't have an Android device setup in your emulator as detailed in other answers on this page.

How to get VM arguments from inside of Java application?

I haven't tried specifically getting the VM settings, but there is a wealth of information in the JMX utilities specifically the MXBean utilities. This would be where I would start. Hopefully you find something there to help you.

The sun website has a bunch on the technology:

http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html

How to change btn color in Bootstrap

2019 Update for Bootstrap 4

Now that Bootstrap 4 uses SASS, you can easily change the primary button color using the button-variant mixins:

$mynewcolor:#77cccc;

.btn-primary {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}
    
.btn-outline-primary {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}

https://codeply.com/go/2bHYxYSC0n (SASS demo)

This SASS compiles into the following CSS...

.btn-primary {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:hover {
    color: #212529;
    background-color: #52bebe;
    border-color: #8ad3d3
}

.btn-primary:focus,
.btn-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-primary.disabled,
.btn-primary:disabled {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:not(:disabled):not(.disabled):active,
.btn-primary:not(:disabled):not(.disabled).active,
.show>.btn-primary.dropdown-toggle {
    color: #212529;
    background-color: #9cdada;
    border-color: #2e7c7c
}

.btn-primary:not(:disabled):not(.disabled):active:focus,
.btn-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-outline-primary {
    color: #7cc;
    background-color: transparent;
    background-image: none;
    border-color: #7cc
}

.btn-outline-primary:hover {
    color: #222;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:focus,
.btn-outline-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

.btn-outline-primary.disabled,
.btn-outline-primary:disabled {
    color: #7cc;
    background-color: transparent
}

.btn-outline-primary:not(:disabled):not(.disabled):active,
.btn-outline-primary:not(:disabled):not(.disabled).active,
.show>.btn-outline-primary.dropdown-toggle {
    color: #212529;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:not(:disabled):not(.disabled):active:focus,
.btn-outline-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-outline-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

https://codeply.com/go/lD3tUE01lo (CSS demo)


To change the primary color for all classes see: Customizing Bootstrap CSS template and How to change the bootstrap primary color?

How can a windows service programmatically restart itself?

Just passing: and thought i would add some extra info...

you can also throw an exception, this will auto close the windows service, and the auto re-start options just kick in. the only issue with this is that if you have a dev enviroment on your pc then the JIT tries to kick in, and you will get a prompt saying debug Y/N. say no and then it will close, and then re-start properly. (on a PC with no JIT it just all works). the reason im trolling, is this JIT is new to Win 7 (it used to work fine with XP etc) and im trying to find a way of disabling the JIT.... i may try the Environment.Exit method mentioned here see how that works too.

Kristian : Bristol, UK

C# Creating an array of arrays

What you need to do is this:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]> type:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

Pandas: Convert Timestamp to datetime.date

You can convert a datetime.date object into a pandas Timestamp like this:

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

import pandas as pd
import datetime

# create a datetime data object
d_time = datetime.date(2010, 11, 12)

# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')

# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)

# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)

# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)

How to check whether an array is empty using PHP?

Why has no one said this answer:

$array = [];

if($array == []) {
    // array is empty
}

How to give a user only select permission on a database

For the GUI minded people, you can:

  • Right click the Database in Management Studio.
  • Choose Properties
  • Select Permissions
  • If your user does not show up in the list, choose Search and type their name
  • Select the user in the Users or Roles list
  • In the lower window frame, Check the Select permission under the Grant column

Create table with jQuery - append

It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/

In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:

Example #1

ul>li*5

... will produce

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Example #2

div#header+div.page+div#footer.class1.class2.class3

... will produce

<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>

And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/

And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js

How to embed a PDF?

This works perfectly and this is official html5.

<object data="https://link-to-pdf"></object>

Can I set enum start value in Java?

 public class MyClass {
    public static void main(String args[]) {
     Ids id1 = Ids.OPEN;
     System.out.println(id1.getValue());
    }
}

enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

@scottf, You probably confused because of the constructor defined in the ENUM.

Let me explain that.

When class loader loads enum class, then enum constructor also called. On what!! Yes, It's called on OPEN and close. With what values 100 for OPEN and 200 for close

Can I have different value?

Yes,

public class MyClass {
    public static void main(String args[]) {
     Ids id1 = Ids.OPEN;
     id1.setValue(2);
     System.out.println(id1.getValue());
    }
}

enum Ids {
    OPEN(100), CLOSE(200);

    private int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
    public void setValue(int value) { id = value; }
}

But, It's bad practice. enum is used for representing constants like days of week, colors in rainbow i.e such small group of predefined constants.

Get data from file input in JQuery

Html:

<input type="file" name="input-file" id="input-file">

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

For date:

#!/usr/bin/ruby -w

date = Time.new
#set 'date' equal to the current date/time. 

date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY

puts date
#output the date

The above will display, for example, 10/01/15

And for time

time = Time.new
#set 'time' equal to the current time. 

time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and           minute

puts time
#output the time

The above will display, for example, 11:33

Then to put it together, add to the end:

puts date + " " + time

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

Execute multiple command lines with the same process using .NET

You can redirect standard input and use a StreamWriter to write to it:

        Process p = new Process();
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "cmd.exe";
        info.RedirectStandardInput = true;
        info.UseShellExecute = false;

        p.StartInfo = info;
        p.Start();

        using (StreamWriter sw = p.StandardInput)
        {
            if (sw.BaseStream.CanWrite)
            {
                sw.WriteLine("mysql -u root -p");
                sw.WriteLine("mypassword");
                sw.WriteLine("use mydb;");
            }
        }

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

The property 'Id' is part of the object's key information and cannot be modified

There are two types of associations. Independant association where the related key would only surface as navigation property. Second one is foreign key association where the related key can be changed using foreign key and navigation property. So you can do the following.

//option 1 generic option

var contacttype = new ContactType{Id = 3};
db.ContactTypes.Attach(contacttype);
customer.ContactType = contacttype;

option 2 foreign key option

contact.ContactTypeId = 3;

//generic option works with foreign key and independent association

contact.ContactReference.EntityKey = new EntityKey("container.contactset","contacttypeid",3);

Collapse all methods in Visual Studio Code

Use Ctrl + K + 0 to fold all and Ctrl + K + J to unfold all.

Bash script to run php script

If you don't do anything in your bash script than run the php one, you could simply run the php script from cron with a command like /usr/bin/php /path/to/your/file.php.

How to make android listview scrollable?

This is my working code. you may try with this.

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listEmployeeDetails"
        android:layout_height="match_parent" 
        android:layout_width="match_parent"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_gravity="center"
        android:background="#ffffff">

        <TextView android:id="@+id/tvEmpId"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.3"/>
            <TextView android:id="@+id/tvNameEmp"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"                     
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.5"/>
             <TextView
                    android:layout_height="wrap_content"
                    android:id="@+id/tvStatusEmp"
                    android:textSize="12sp"
                    android:padding="2dp"
                    android:layout_width="0dp"
                    android:layout_weight="0.2"/>               
</LinearLayout> 

details.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listEmployeeDetails"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/page_bg"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/lLayoutGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/page_bg"
        android:orientation="vertical" >

        ................... others components here............................

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alwaysDrawnWithCache="true"
            android:dividerHeight="1dp"
            android:horizontalSpacing="3dp"
            android:scrollingCache="true"
            android:smoothScrollbar="true"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dp" 
            android:layout_marginBottom="30dp">
        </ListView>
    </LinearLayout>
</RelativeLayout>

Adapter class :

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {
    private Context context;
    private List<EmployeeBean> employeeList; 

    publicListViewAdapter(Context context, List<EmployeeBean> employeeList) {
            this.context = context;
            this.employeeList = employeeList;
        }

    public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            EmployeeBeanHolder holder = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.row, parent, false);

            holder = new EmployeeBeanHolder();
            holder.employeeBean = employeeList.get(position);
            holder.tvEmpId = (TextView) row.findViewById(R.id.tvEmpId);
            holder.tvName = (TextView) row.findViewById(R.id.tvNameEmp);
            holder.tvStatus = (TextView) row.findViewById(R.id.tvStatusEmp);

            row.setTag(holder);
            holder.tvEmpId.setText(holder.employeeBean.getEmpId());
            holder.tvName.setText(holder.employeeBean.getName());
            holder.tvStatus.setText(holder.employeeBean.getStatus());

             if (position % 2 == 0) {
                    row.setBackgroundColor(Color.rgb(213, 229, 241));
                } else {                    
                    row.setBackgroundColor(Color.rgb(255, 255, 255));
                }        

            return row;
        }

   public static class EmployeeBeanHolder {
        EmployeeBean employeeBean;
        TextView tvEmpId;
        TextView tvName;
        TextView tvStatus;
    }

    @Override
    public int getCount() {
            return employeeList.size();
        }

    @Override
    public Object getItem(int position) {
            return null;
        }

    @Override
    public long getItemId(int position) {
            return 0;
    }
}

employee bean class:

public class EmployeeBean {
    private String empId;
    private String name;
    private String status;

    public EmployeeBean(){      
    }

    public EmployeeBean(String empId, String name, String status) {
        this.empId= empId;
        this.name = name;
        this.status = status;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId= empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status =status;
    }
}

in Activity class:

onCreate method:

public static List<EmployeeBean> EMPLOYEE_LIST = new ArrayList<EmployeeBean>();

//create emplyee data
for(int i=0;i<=10;i++) {
  EmployeeBean emplyee = new EmployeeBean("EmpId"+i,"Name "+i, "Active");
  EMPLOYEE_LIST .add(emplyee );
}

ListView listView;
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ListViewAdapter(this, EMPLOYEE_LIST));

IIS: Where can I find the IIS logs?

I believe this is an easier way of knowing where your IIS logs are, rather than just assuming a default location:

Go to your IIS site, e.g. Default, click on it, and you should see "Logging" to the right if logging is enabled:

enter image description here

Open it and you should see the folder right there:

enter image description here

You are welcome!

How to add spacing between columns?

To obtain a particular width of spacing between columns, we have to set up padding in the standard Bootstrap's layout.

_x000D_
_x000D_
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');_x000D_
_x000D_
/* Check breakpoint at http://getbootstrap.com/css/#grid-media-queries */_x000D_
@media (min-width: 992px) { _x000D_
  .space-100-px > .row > .col-md-6:first-child {_x000D_
    padding: 0 50px 0 0; /* The first half of 100px */_x000D_
  }_x000D_
  .space-100-px > .row > .col-md-6:last-child {_x000D_
    padding: 0 0 0 50px; /* The second half of 100px */_x000D_
  }_x000D_
}_x000D_
_x000D_
/* The result will be easier to see. */ _x000D_
.space-100-px img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<div class="container-fluid space-100-px">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <img src="http://placehold.it/450x100?text=Left" alt="Left">_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <img src="http://placehold.it/450x100?text=Right" alt="Right">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

asp:TextBox ReadOnly=true or Enabled=false?

If a control is disabled it cannot be edited and its content is excluded when the form is submitted.

If a control is readonly it cannot be edited, but its content (if any) is still included with the submission.

HTTP Request in Kotlin

If you are using Kotlin, you might as well keep your code as succinct as possible. The run method turns the receiver into this and returns the value of the block. this as HttpURLConnection creates a smart cast. bufferedReader().readText() avoids a bunch of boilerplate code.

return URL(url).run {
        openConnection().run {
            this as HttpURLConnection
            inputStream.bufferedReader().readText()
        }
}

You can also wrap this into an extension function.

fun URL.getText(): String {
    return openConnection().run {
                this as HttpURLConnection
                inputStream.bufferedReader().readText()
            }
}

And call it like this

return URL(url).getText()

Finally, if you are super lazy, you can extend the String class instead.

fun String.getUrlText(): String {
    return URL(this).run {
            openConnection().run {
                this as HttpURLConnection
                inputStream.bufferedReader().readText()
            }
    }
}

And call it like this

return "http://somewhere.com".getUrlText()

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Rather than allocating a massive array, could you try utilizing an iterator? These are delay-executed, meaning values are generated only as they're requested in an foreach statement; you shouldn't run out of memory this way:

private static IEnumerable<double> MakeRandomNumbers(int numberOfRandomNumbers) 
{
    for (int i = 0; i < numberOfRandomNumbers; i++)
    {
        yield return randomGenerator.GetAnotherRandomNumber();
    }
}


...

// Hooray, we won't run out of memory!
foreach(var number in MakeRandomNumbers(int.MaxValue))
{
    Console.WriteLine(number);
}

The above will generate as many random numbers as you wish, but only generate them as they're asked for via a foreach statement. You won't run out of memory that way.

Alternately, If you must have them all in one place, store them in a file rather than in memory.

Autoplay audio files on an iPad with HTML5

As of iOS 4.2.1, neither the fake click nor the .load() trick will work to autoplay audio on any iOS device. The only option I know of is to have the user actually perform a click action and begin playback in the click event handler without wrapping the .play() call in anything asynchronous (ajax, setTimeout, etc).

Someone please tell me if I'm mistaken. I had working loopholes for both iPad and iPhone before the most recent update, and all of them look like they've been closed.

Convert char to int in C and C++

I was having problems converting a char array like "7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e" into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.

This separates the char string into its right integers, and may be helpful to more people than just me ;)

unsigned int* char2int(char *a, int len)
{
    int i,u;
    unsigned int *val = malloc(len*sizeof(unsigned long));

    for(i=0,u=0;i<len;i++){
        if(i%2==0){
            if(a[i] <= 57)
                val[u] = (a[i]-50)<<4;
            else
                val[u] = (a[i]-55)<<4;
        }
        else{
            if(a[i] <= 57)
                val[u] += (a[i]-50);
            else
                val[u] += (a[i]-55);
            u++;
        }
    }
    return val;
}

Hope it helps!

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Lots of potential solutions, but let's add just one more. Use Jackson (JSON processing lib) to do "json-less" conversion, like:

ObjectMapper m = new ObjectMapper();
Map<String,Object> props = m.convertValue(myBean, Map.class);
MyBean anotherBean = m.convertValue(props, MyBean.class);

(this blog entry has some more examples)

You can basically convert any compatible types: compatible meaning that if you did convert from type to JSON, and from that JSON to result type, entries would match (if configured properly can also just ignore unrecognized ones).

Works well for cases one would expect, including Maps, Lists, arrays, primitives, bean-like POJOs.

Run an Ansible task only when the variable contains a specific string

I used

failed_when: not(promtool_version.stdout.find('1.5.2') != -1)

means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.

Find kth smallest element in a binary search tree in Optimum way

For not balanced searching tree, it takes O(n).

For balanced searching tree, it takes O(k + log n) in the worst case but just O(k) in Amortized sense.

Having and managing the extra integer for every node: the size of the sub-tree gives O(log n) time complexity. Such balanced searching tree is usually called RankTree.

In general, there are solutions (based not on tree).

Regards.

How to escape single quotes in MySQL

Put quite simply:

SELECT 'This is Ashok''s Pen.';

So inside the string, replace each single quote with two of them.

Or:

SELECT 'This is Ashok\'s Pen.'

Escape it =)

How to get last month/year in java?

Your solution is here but instead of addition you need to use subtraction

c.add(Calendar.MONTH, -1);

Then you can call getter on the Calendar to acquire proper fields

int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year  = c.get(Calendar.YEAR);

Mythical man month 10 lines per developer day - how close on large projects?

One suspects this perennial bit of manager-candy was coined when everything was a sys app written in C because if nothing else the magic number would vary by orders of magnitude depending on the language, scale and nature of the application. And then you have to discount comments and attributes. And ultimately who cares about the number of lines of code written? Are you supposed to be finished when you've reach 10K lines? 100K? So arbitrary.

It's useless.

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));
}

Will iOS launch my app into the background if it was force-quit by the user?

The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.

In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.

PushKit reference from Apple:

The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.

To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

Ubuntu: OpenJDK 8 - Unable to locate package

I was having the same issue and tried all of the solutions on this page but none of them did the trick.

What finally worked was adding the universe repo to my repo list. To do that run the following command

sudo add-apt-repository universe

After running the above command I was able to run

sudo apt install openjdk-8-jre

without an issue and the package was installed.

Hope this helps someone.

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

Get selected option from select element

The above would very well work, but it seems you have missed the jQuery typecast for the dropdown text. Other than that it would be advisable to use .val() to set text for an input text type element. With these changes the code would look like the following:

    $('#txtEntry2').val($('#ddlCodes option:selected').text());

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

Maven Out of Memory Build Failure

While building the project on Unix/Linux platform, set Maven options syntax as below. Notice that single qoutation signs, not double qoutation.

export MAVEN_OPTS='-Xmx512m -XX:MaxPermSize=128m'

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

How do I update an entity using spring-data-jpa?

As what has already mentioned by others, the save() itself contains both create and update operation.

I just want to add supplement about what behind the save() method.

Firstly, let's see the extend/implement hierarchy of the CrudRepository<T,ID>, enter image description here

Ok, let's check the save() implementation at SimpleJpaRepository<T, ID>,

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

As you can see, it will check whether the ID is existed or not firstly, if the entity is already there, only update will happen by merge(entity) method and if else, a new record is inserted by persist(entity) method.

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

I have observed a quote ' in your 1st line and also at the end of your last line.

'using System.Collections.Generic;

Is this present in your original code or some formatting mistake?

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Length of a JavaScript object

If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:

  1. Run either Object.keys() to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames() if you want to also include the names of properties that are not enumerable.
  2. Get the .length property of that array.

If you need to do this more than once, you could wrap this logic in a function:

function size(obj, enumerablesOnly) {
    return enumerablesOnly === false ?
        Object.getOwnPropertyNames(obj).length :
        Object.keys(obj).length;
}

How to use this particular function:

var myObj = Object.create({}, {
    getFoo: {},
    setFoo: {}
});
myObj.Foo = 12;

var myArr = [1,2,5,4,8,15];

console.log(size(myObj));        // Output : 1
console.log(size(myObj, true));  // Output : 1
console.log(size(myObj, false)); // Output : 3
console.log(size(myArr));        // Output : 6
console.log(size(myArr, true));  // Output : 6
console.log(size(myArr, false)); // Output : 7

See also this Fiddle for a demo.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I was so confusing first time, but I propose you final working solution for Windows:

1) Open cmd and go to your Java/jdk/bin directory (just press cd .. to go one folder back and cd NAME_FOLDER to go one folder forward), in my case, final folder: C:\Program Files\Java\jdk1.8.0_73\bin> enter image description here

2) Now type this command keytool -list -v -keystore C:\Users\YOUR_WINDOWS_USER\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

As result you have to get something like this: enter image description here

How to view file history in Git?

I like to use gitk name_of_file

This shows a nice list of the changes that happened to a file at each commit, instead of showing the changes to all the files. Makes it easier to track down something that happened.

EventListener Enter Key

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}