Programs & Examples On #Iterator range

SQL Switch/Case in 'where' clause

I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.

If you're unable to change the structure, something like the below might work:

SELECT
    *
FROM
    Test
WHERE
    Account_Location = (
        CASE LocationType
          WHEN 'location' THEN @locationID
          ELSE Account_Location
        END
    )
    AND
    Account_Location_Area = (
        CASE LocationType
          WHEN 'area' THEN @locationID
          ELSE Account_Location_Area
        END
    )

And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.

EDIT: The above suggestions are of course much better, just ignore mine.

Content Security Policy: The page's settings blocked the loading of a resource

You can disable them in your browser.

Firefox

Type about:config in the Firefox address bar and find security.csp.enable and set it to false.

Chrome

You can install the extension called Disable Content-Security-Policy to disable CSP.

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${default.javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${default.javax.servlet.jsp.version}</version>
            <scope>provided</scope>
        </dependency>

In Python, what does dict.pop(a,b) mean?

The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs

The second argument, default, is what pop returns if the first argument, key, is absent. (If you call pop with just one argument, key, it raises an exception if that key's absent).

In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:

b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data

you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).

What are some resources for getting started in operating system development?

A simple and basic OS development tutorial designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related paper is here.

How to wrap async function calls into a sync function in Node.js or Javascript?

I can't find a scenario that cannot be solved using node-fibers. The example you provided using node-fibers behaves as expected. The key is to run all the relevant code inside a fiber, so you don't have to start a new fiber in random positions.

Lets see an example: Say you use some framework, which is the entry point of your application (you cannot modify this framework). This framework loads nodejs modules as plugins, and calls some methods on the plugins. Lets say this framework only accepts synchronous functions, and does not use fibers by itself.

There is a library that you want to use in one of your plugins, but this library is async, and you don't want to modify it either.

The main thread cannot be yielded when no fiber is running, but you still can create plugins using fibers! Just create a wrapper entry that starts the whole framework inside a fiber, so you can yield the execution from the plugins.

Downside: If the framework uses setTimeout or Promises internally, then it will escape the fiber context. This can be worked around by mocking setTimeout, Promise.then, and all event handlers.

So this is how you can yield a fiber until a Promise is resolved. This code takes an async (Promise returning) function and resumes the fiber when the promise is resolved:

framework-entry.js

console.log(require("./my-plugin").run());

async-lib.js

exports.getValueAsync = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Async Value");
    }, 100);
  });
};

my-plugin.js

const Fiber = require("fibers");

function fiberWaitFor(promiseOrValue) {
  var fiber = Fiber.current, error, value;
  Promise.resolve(promiseOrValue).then(v => {
    error = false;
    value = v;
    fiber.run();
  }, e => {
    error = true;
    value = e;
    fiber.run();
  });
  Fiber.yield();
  if (error) {
    throw value;
  } else {
    return value;
  }
}

const asyncLib = require("./async-lib");

exports.run = () => {
  return fiberWaitFor(asyncLib.getValueAsync());
};

my-entry.js

require("fibers")(() => {
  require("./framework-entry");
}).run();

When you run node framework-entry.js it will throw an error: Error: yield() called with no fiber running. If you run node my-entry.js it works as expected.

HashMap to return default value for non-found keys?

    public final Map<String, List<String>> stringMap = new ConcurrentHashMap<String, List<String>>() {
        @Nullable
        @Override
        public List<String> get(@NonNull Object key) {
            return computeIfAbsent((String) key, s -> new ArrayList<String>());
        }
    };

HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap,

Random number from a range in a Bash Script

You can get the random number through urandom

head -200 /dev/urandom | cksum

Output:

3310670062 52870

To retrieve the one part of the above number.

head -200 /dev/urandom | cksum | cut -f1 -d " "

Then the output is

3310670062

To meet your requirement,

head -200 /dev/urandom |cksum | cut -f1 -d " " | awk '{print $1%63000+2001}'

error::make_unique is not a member of ‘std’

If you are stuck with c++11, you can get make_unique from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

How do I remove the old history from a git repository?

Maybe it's too late to post a reply, but as this page is the first Google's result, it may still be helpful.

If you want to free some space in your git repo, but do not want to rebuild all your commits (rebase or graft), and still be able to push/pull/merge from people who has the full repo, you may use the git clone shallow clone (--depth parameter).

; Clone the original repo into limitedRepo
git clone file:///path_to/originalRepo limitedRepo --depth=10

; Remove the original repo, to free up some space
rm -rf originalRepo
cd limitedRepo
git remote rm origin

You may be able to shallow your existing repo, by following these steps:

; Shallow to last 5 commits
git rev-parse HEAD~5 > .git/shallow

; Manually remove all other branches, tags and remotes that refers to old commits

; Prune unreachable objects
git fsck --unreachable ; Will show you the list of what will be deleted
git gc --prune=now     ; Will actually delete your data

How to remove all git local tags?

Ps: Older versions of git didn't support clone/push/pull from/to shallow repos.

Filter array to have unique values

I've always used:

unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);

But recently I had to get unique values for:

["1", 1, "2", 2, "3", 3]

And my old standby didn't cut it, so I came up with this:

uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));

How can I load storyboard programmatically from class?

You can always jump right to the root controller:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [storyboard instantiateInitialViewController];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

Best way to find the intersection of multiple sets?

From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

where *a_list is list expansion

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.

JAXB: how to marshall map into <key>value</key>

I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <mapProperty>
      <map>
         <key>value</key>
         <key2>value2</key2>
      </map>
   </mapProperty>
</root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, String> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, String>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> map) {
        this.mapProperty = map;
    }

}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {

    @Override
    public AdaptedMap marshal(Map<String, String> map) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element rootElement = document.createElement("map");
        document.appendChild(rootElement);

        for(Entry<String,String> entry : map.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.setTextContent(entry.getValue());
            rootElement.appendChild(mapElement);
        }

        AdaptedMap adaptedMap = new AdaptedMap();
        adaptedMap.setValue(document);
        return adaptedMap;
    }

    @Override
    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Element rootElement = (Element) adaptedMap.getValue();
        NodeList childNodes = rootElement.getChildNodes();
        for(int x=0,size=childNodes.getLength(); x<size; x++) {
            Node childNode = childNodes.item(x);
            if(childNode.getNodeType() == Node.ELEMENT_NODE) {
                map.put(childNode.getLocalName(), childNode.getTextContent());
            }
        }
        return map;
    }

}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;

public class AdaptedMap {

    private Object value;

    @XmlAnyElement
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

How can I use a reportviewer control in an asp.net mvc 3 razor view?

the documentations refers to an ASP.NET application.
You can try and have a look at my answer here.
I have an example attached to my reply.
Another example for ASP.NET MVC3 can be found here.

How to define a two-dimensional array?

Here is the code snippet for creating a matrix in python:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

Please suggest if I have missed something.

How to start/stop/restart a thread in Java?

It is impossible to terminate a thread unless the code running in that thread checks for and allows termination.

You said: "Sadly I must kill/restart it ... I don't have complete control over the contents of the thread and for my situation it requires a restart"

If the contents of the thread does not allow for termination of its exectuion then you can not terminate that thread.

In your post you said: "My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow()..."

If you look at the source of "shutdownnow" it just runs through and interrupts the currently running threads. This will not stop their execution unless the code in those threads checks to see if it has been ineterrupted and, if so, stops execution itself. So shutdownnow is probably not doing what you think.

Let me illustrate what I mean when I say that the contents of the thread must allow for that thread to be terminated:

myExecutor.execute(new Runnable() {
 public void run() {
  while (true) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

That thread will continue to run forever, even though shutdownnow was called, because it never checks to see if it has been terminated or not. This thread, however, will shut down:

myExecutor.execute(new Runnable() {
 public void run() {
  while (!Thread.interrupted()) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

Since this thread checks to see whether or not it has been interrupted / shut down / terminated.

So if you want a thread that you can shut down, you need to make sure it checks to see if it has been interrupted. If you want a thread that you can "shut down" and "restart" you can make a runnable that can take new tasks as was mentioned before.

Why can you not shut down a running thread? Well I actually lied, you can call "yourThread.stop()" but why is this a bad idea? The thread could be in a synchronized (or other critical section, but we will limit ourselves to setions guarded by the syncrhonized key word here) section of code when you stop it. synch blocks are supposed to be executed in their entirity and only by one thread before being accessed by some other thread. If you stop a thread in the middle of a synch block, the protection put into place by the synch block is invalidated and your program will get into an unknown state. Developers make put stuff in synch blocks to keep things in synch, if you use threadInstance.stop() you destroy the meaning of synchronize, what the developer of that code was trying to accomplish and how the developer of that code expected his synchronized blocks to behave.

What is the meaning of "Failed building wheel for X" in pip install?

I got the same message when I tried to install pip install django-imagekit. So I ran pip install wheel (I had python 2.7) and then I reran pip install django-imagekit and it worked. Thanks

Extension gd is missing from your system - laravel composer Update

The solution is quite simple.

In your php.ini, just uncomment the line extension=php_gd2.dll (or .so extension for unix systems.)

Hope it helps.

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

What is the result of % in Python?

In most languages % is used for modulus. Python is no exception.

Get column index from column name in python pandas

Here is a solution through list comprehension. cols is the list of columns to get index for:

[df.columns.get_loc(c) for c in cols if c in df]

Thymeleaf using path variables to th:href

A cleaner and easier way to do this

<a href="somepage.html" th:href="@{|/my/url/${variable}|}">A Link</a>

I found this solution in Thymeleaf Documentation on "4.8 Literal substitutions".

Query to list number of records in each table in a database

A snippet I found at http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=21021 that helped me:

select t.name TableName, i.rows Records
from sysobjects t, sysindexes i
where t.xtype = 'U' and i.id = t.id and i.indid in (0,1)
order by TableName;

What is the difference between Sublime text and Github's Atom

One major difference that no one has pointed out so far and that might be important to some people is that (at least on Windows) Atom doesn't fully support other keyboard layouts than US. There is an bug report on that with a few hundred posts that has been open for more than a year now (https://github.com/atom/atom-keymap/issues/35).

Might be relevant when choosing an editor.

How to handle the `onKeyPress` event in ReactJS?

React is not passing you the kind of events you might think. Rather, it is passing synthetic events.

In a brief test, event.keyCode == 0 is always true. What you want is event.charCode

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Looping through JSON with node.js

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

How to find length of digits in an integer?

For posterity, no doubt by far the slowest solution to this problem:

def num_digits(num, number_of_calls=1):
    "Returns the number of digits of an integer num."
    if num == 0 or num == -1:
        return 1 if number_of_calls == 1 else 0
    else:
        return 1 + num_digits(num/10, number_of_calls+1)

Subtract a value from every number in a list in Python?

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])

Compiling/Executing a C# Source File in Command Prompt

In Windows systems, use the command csc <filname>.cs in the command prompt while the current directory is in Microsoft Visual Studio\<Year>\<Version>

There are two ways:

Using the command prompt:

  1. Start --> Command Prompt
  2. Change the directory to Visual Studio folder, using the command: cd C:\Program Files (x86)\Microsoft Visual Studio\2017\ <Version>
  3. Use the command: csc /.cs

Using Developer Command Prompt :

  1. Start --> Developer Command Prompt for VS 2017 (Here the directory is already set to Visual Studio folder)

  2. Use the command: csc /.cs

Hope it helps!

Understanding inplace=True

As Far my experience in pandas I would like to answer.

The 'inplace=True' argument stands for the data frame has to make changes permanent eg.

    df.dropna(axis='index', how='all', inplace=True)

changes the same dataframe (as this pandas find NaN entries in index and drops them). If we try

    df.dropna(axis='index', how='all')

pandas shows the dataframe with changes we make but will not modify the original dataframe 'df'.

Datatable select method ORDER BY clause

Use

datatable.select("col1='test'","col1 ASC")

Then before binding your data to the grid or repeater etc, use this

datatable.defaultview.sort()

That will solve your problem.

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

List of encodings that Node.js supports

If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:

npm install iconv

npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz

> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild

gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.

Can't load IA 32-bit .dll on a AMD 64-bit platform

Go to

Project properties >> Run >> VM options

and put this address:

-Djava.library.path="C:\opencv\build\java\x64"

Node.js project naming conventions for files & folders

Use kebab-case for all package, folder and file names.

Why?

You should imagine that any folder or file might be extracted to its own package some day. Packages cannot contain uppercase letters.

New packages must not have uppercase letters in the name. https://docs.npmjs.com/files/package.json#name

Therefore, camelCase should never be used. This leaves snake_case and kebab-case.

kebab-case is by far the most common convention today. The only use of underscores is for internal node packages, and this is simply a convention from the early days.

Import MySQL database into a MS SQL Server

I had a very similar issue today - I needed to copy a big table(5 millions rows) from MySql into MS SQL.

Here are the steps I've done(under Ubuntu Linux):

  1. Created a table in MS SQL which structure matches the source table in MySql.

  2. Installed MS SQL command line: https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-tools#ubuntu

  3. Dumped table from MySql to a file:

mysqldump \
    --compact \
    --complete-insert \
    --no-create-info \
    --compatible=mssql \
    --extended-insert=FALSE \
    --host "$MYSQL_HOST" \
    --user "$MYSQL_USER" \
    -p"$MYSQL_PASS" \
    "$MYSQL_DB" \
    "$TABLE" > "$FILENAME"
  1. In my case the dump file was quite large, so I decided to split it into a number of small pieces(1000 lines each) - split --lines=1000 "$FILENAME" part-

  2. Finally I iterated over these small files, did some text replacements, and executed the pieces one by one against MS SQL server:

export SQLCMD=/opt/mssql-tools/bin/sqlcmd

x=0

for file in part-*
do
  echo "Exporting file [$file] into MS SQL. $x thousand(s) processed"

  # replaces \' with ''
  sed -i "s/\\\'/''/g" "$file"

  # removes all "
  sed -i 's/"//g' "$file"

  # allows to insert records with specified PK(id)
  sed -i "1s/^/SET IDENTITY_INSERT $TABLE ON;\n/" "$file"

  "$SQLCMD" -S "$AZURE_SERVER" -d "$AZURE_DB" -U "$AZURE_USER" -P "$AZURE_PASS" -i "$file"
  echo ""
  echo ""

  x=$((x+1))
done

echo "Done"

Of course you'll need to replace my variables like $AZURE_SERVER, $TABLE , e.t.c. with yours.

Hope that helps.

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

Looking at most of the replies, they seem overly complicated. Angular has built in mechanisms to unregister.

Use the deregistration function returned by $on :

// Register and get a handle to the listener
var listener = $scope.$on('someMessage', function () {
    $log.log("Message received");
});

// Unregister
$scope.$on('$destroy', function () {
    $log.log("Unregistering listener");
    listener();
});

Where are environment variables stored in the Windows Registry?

CMD:

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment

PowerShell:

Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment

Powershell/.NET: (see EnvironmentVariableTarget Enum)

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

constant pointer vs pointer on a constant value

char * const a;

*a is writable, but a is not; in other words, you can modify the value pointed to by a, but you cannot modify a itself. a is a constant pointer to char.

const char * a; 

a is writable, but *a is not; in other words, you can modify a (pointing it to a new location), but you cannot modify the value pointed to by a.

Note that this is identical to

char const * a;

In this case, a is a pointer to a const char.

What is the difference between match_parent and fill_parent?

They're the same thing (in API Level 8+). Use match_parent.

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)

...

fill_parent: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent.

http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

Create tap-able "links" in the NSAttributedString of a UILabel?

Here is a swift version of NAlexN's answer.

class TapabbleLabel: UILabel {

let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
var textStorage = NSTextStorage() {
    didSet {
        textStorage.addLayoutManager(layoutManager)
    }
}

var onCharacterTapped: ((label: UILabel, characterIndex: Int) -> Void)?

let tapGesture = UITapGestureRecognizer()

override var attributedText: NSAttributedString? {
    didSet {
        if let attributedText = attributedText {
            textStorage = NSTextStorage(attributedString: attributedText)
        } else {
            textStorage = NSTextStorage()
        }
    }
}

override var lineBreakMode: NSLineBreakMode {
    didSet {
        textContainer.lineBreakMode = lineBreakMode
    }
}

override var numberOfLines: Int {
    didSet {
        textContainer.maximumNumberOfLines = numberOfLines
    }
}

/**
 Creates a new view with the passed coder.

 :param: aDecoder The a decoder

 :returns: the created new view.
 */
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setUp()
}

/**
 Creates a new view with the passed frame.

 :param: frame The frame

 :returns: the created new view.
 */
override init(frame: CGRect) {
    super.init(frame: frame)
    setUp()
}

/**
 Sets up the view.
 */
func setUp() {
    userInteractionEnabled = true
    layoutManager.addTextContainer(textContainer)
    textContainer.lineFragmentPadding = 0
    textContainer.lineBreakMode = lineBreakMode
    textContainer.maximumNumberOfLines = numberOfLines
    tapGesture.addTarget(self, action: #selector(TapabbleLabel.labelTapped(_:)))
    addGestureRecognizer(tapGesture)
}

override func layoutSubviews() {
    super.layoutSubviews()
    textContainer.size = bounds.size
}

func labelTapped(gesture: UITapGestureRecognizer) {
    guard gesture.state == .Ended else {
        return
    }

    let locationOfTouch = gesture.locationInView(gesture.view)
    let textBoundingBox = layoutManager.usedRectForTextContainer(textContainer)
    let textContainerOffset = CGPoint(x: (bounds.width - textBoundingBox.width) / 2 - textBoundingBox.minX,
                                      y: (bounds.height - textBoundingBox.height) / 2 - textBoundingBox.minY)        
    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouch.x - textContainerOffset.x,
                                                 y: locationOfTouch.y - textContainerOffset.y)
    let indexOfCharacter = layoutManager.characterIndexForPoint(locationOfTouchInTextContainer,
                                                                inTextContainer: textContainer,
                                                                fractionOfDistanceBetweenInsertionPoints: nil)

    onCharacterTapped?(label: self, characterIndex: indexOfCharacter)
}
}

You can then create an instance of that class inside your viewDidLoad method like this:

let label = TapabbleLabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[view]-|",
                                               options: [], metrics: nil, views: ["view" : label]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[view]-|",
                                               options: [], metrics: nil, views: ["view" : label]))

let attributedString = NSMutableAttributedString(string: "String with a link", attributes: nil)
let linkRange = NSMakeRange(14, 4); // for the word "link" in the string above

let linkAttributes: [String : AnyObject] = [
    NSForegroundColorAttributeName : UIColor.blueColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue,
    NSLinkAttributeName: "http://www.apple.com"]
attributedString.setAttributes(linkAttributes, range:linkRange)

label.attributedText = attributedString

label.onCharacterTapped = { label, characterIndex in
    if let attribute = label.attributedText?.attribute(NSLinkAttributeName, atIndex: characterIndex, effectiveRange: nil) as? String,
        let url = NSURL(string: attribute) {
        UIApplication.sharedApplication().openURL(url)
    }
}

It's better to have a custom attribute to use when a character is tapped. Now, it's the NSLinkAttributeName, but could be anything and you can use that value to do other things other than opening a url, you can do any custom action.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Thanks to Maarten (Query a collection using PropertyInfo object in LINQ) I got this solution:

myList.OrderByDescending(x => myPropertyInfo.GetValue(x, null)).ToList();

In my case I was working on a "ColumnHeaderMouseClick" (WindowsForm) so just found the specific Column pressed and its correspondent PropertyInfo:

foreach (PropertyInfo column in (new Process()).GetType().GetProperties())
{
    if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)
    {}
}

OR

PropertyInfo column = (new Process()).GetType().GetProperties().Where(x => x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();

(be sure to have your column Names matching the object Properties)

Cheers

Disable Laravel's Eloquent timestamps

Simply place this line in your Model:

public $timestamps = false;

And that's it!


Example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public $timestamps = false;

    //
}

To disable timestamps for one operation (e.g. in a controller):

$post->content = 'Your content'; 
$post->timestamps = false; // Will not modify the timestamps on save
$post->save();

To disable timestamps for all of your Models, create a new BaseModel file:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    public $timestamps = false;

    //
}

Then extend each one of your Models with the BaseModel, like so:

<?php

namespace App;

class Post extends BaseModel
{
    //
}

How do I ignore files in Subversion?

Use the command svn status on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.

As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html. The book also describes more about using svn status.

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

Querying a linked sql server

try Select * from openquery("aa-db-dev01",'Select * from users') ,the database connection should be defined in he linked server configuration

How to get just one file from another branch

Supplemental to VonC's and chhh's answers.

git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative than just use
git show experiment:app.js > app.js

or

git checkout experiment -- app.js

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

How can I disable a button in a jQuery dialog from a function?

If anybody is looking to replace a button with something like a loading animation when clicked (for example when a "Submit" button submits the form in the dialog) - you can replace the button with your image like this:

...
buttons: {
    "Submit": function(evt) {
        $(evt.target).closest('button').replaceWith('<img src="loading.gif">');
    }
}

jQuery replaceWith docs

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

Could you explain STA and MTA?

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

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

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

time delayed redirect?

Include this code somewhere when you slide to your 'section' called blog.

$("#myLink").click(function() {
    setTimeout(function() {
        window.navigate("the url of the page you want to navigate back to");
    }, 2000);
});

Where myLink is the id of your href.

Can we write our own iterator in Java?

You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.

How to sort a list of objects based on an attribute of the objects?

from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">

or

<form accept-charset="UTF-8">

to force the encoding.

Some references :

http://www.htmlhelp.com/reference/html40/forms/form.html

http://www.w3schools.com/tags/tag_form.asp

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

This would require a sort (O(n log n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:

var maxObject = list.OrderByDescending(item => item.Height).First();

Note that this has the advantage of enumerating the list sequence just once. While it might not matter if list is a List<T> that doesn't change in the meantime, it could matter for arbitrary IEnumerable<T> objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own MaxObject extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):

static class EnumerableExtensions {
    public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector)
      where U : IComparable<U> {
       if (source == null) throw new ArgumentNullException("source");
       bool first = true;
       T maxObj = default(T);
       U maxKey = default(U);
       foreach (var item in source) {
           if (first) {
                maxObj = item;
                maxKey = selector(maxObj);
                first = false;
           } else {
                U currentKey = selector(item);
                if (currentKey.CompareTo(maxKey) > 0) {
                    maxKey = currentKey;
                    maxObj = item;
                }
           }
       }
       if (first) throw new InvalidOperationException("Sequence is empty.");
       return maxObj;
    }
}

and use it with:

var maxObject = list.MaxObject(item => item.Height);

Compute mean and standard deviation by group for multiple variables in a data.frame

This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate like this (assuming DF is the input data frame):

ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))

Note 1: A commenter pointed out that ag is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag has the same number of columns as the input DF. Its first column ag[[1]] is ID and the ith column of the remainder ag[[i+1]] (or equivalanetly ag[-1][[i]]) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j] which can also be written as ag[-1][[i]][, j] .

On the other hand, suppose there are k statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]] or equivalently ag[-1][[k*(i-1)+j]] .

For example, compare the simplicity of the first expression vs. the second:

ag[-1][[2]]
##        mean      sd
## [1,] 36.333 10.2144
## [2,] 32.250  4.1932
## [3,] 43.500  4.9497

ag_flat <- do.call("data.frame", ag) # flatten
ag_flat[-1][, 2 * (2-1) + 1:2]
##   Obs_2.mean Obs_2.sd
## 1     36.333  10.2144
## 2     32.250   4.1932
## 3     43.500   4.9497

Note 2: The input in reproducible form is:

Lines <- "ID  Obs_1   Obs_2   Obs_3
1   43      48      37
1   27      29      22
1   36      32      40
2   33      38      36
2   29      32      27
2   32      31      35
2   25      28      24
3   45      47      42
3   38      40      36"
DF <- read.table(text = Lines, header = TRUE)

How do I create a copy of an object in PHP?

Just to clarify PHP uses copy on write, so basically everything is a reference until you modify it, but for objects you need to use clone and the __clone() magic method like in the accepted answer.

How does Google calculate my location on a desktop?

I am currently in Tokyo, and I used to be in Switzerland. Yet, my location until some days ago was not pinpinted exactly, except in the broad Tokyo area. Today I tried, and I appear to be in Switzerland. How?

Well the secret is that I am now connected through wireless, and my wireless router has been identified (thanks to association to other wifis around me at that time) in a very accurate area in Switzerland. Now, my wifi moved to Tokyo, but the queried system still thinks the wifi router is in Switzerland, because either it has no information about the additional wifis surrounding me right now, or it cannot sort out the conflicting info (namely, the specific info about my wifi router against my ip geolocation, which pinpoints me in the far east).

So, to answer your question, google, or someone for him, did "wardriving" around, mapping the wifi presence. Every time a query is performed to the system (probably in compliance with the W3C draft for the geolocation API) your computer sends the wifi identifiers it sees, and the system does two things:

  1. queries its database if geolocation exists for some of the wifis you passed, and returns the "wardrived" position if found, eventually with triangulation if intensities are present. The more wifi networks around, the higher is the accuracy of the positioning.
  2. adds additional networks you see that are currently not in the database to their database, so they can be reused later.

As you see, the system builds up by itself. The only thing you need is good seeding. After that, it extends in "50 meters chunks" (the range of a newly found wifi connection).

Of course, if you really want the system go banana, you can start exchanging wifi routers around the globe with fellow revolutionaries of the no-global-positioning movement.

Find the greatest number in a list of numbers

max is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)

print(max([9, 7, 12, 5]))

# prints 12 

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

Copying files into the application folder at compile time

Personally I prefer this way.

Modify the .csproj to add

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\MyFirstConfigFile.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

or generalizing, if you want to copy all subfolders and files, you could do:

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\**">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(RecursiveDir)\%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

Program does not contain a static 'Main' method suitable for an entry point

As what, I guess pixparker wanted to say, but remained to be not clear enough, for me at least, do ensure that... All "Other Projects" have an "Output Type" of "Class Library" selected while... Only "One Project" being selected as either "Window Application" or "Console Application" output.

Why doesn't Git ignore my specified file?

.gitignore will only ignore files that you haven't already added to your repository.

If you did a git add ., and the file got added to the index, .gitignore won't help you. You'll need to do git rm sites/default/settings.php to remove it, and then it will be ignored.

Why does CSS not support negative padding?

Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.

Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.

The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
  margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
  margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
  padding: 10px;_x000D_
  background: lightgray;_x000D_
}_x000D_
ul {_x000D_
  list-style: none;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  padding: 0;/* just to reset */_x000D_
  padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
  flex: 1 1 auto;_x000D_
  margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
  <li>a lacinia purus porttitor eget</li>_x000D_
  <li>donec ut nunc lorem</li>_x000D_
  <li>duis in est dictum</li>_x000D_
  <li>tempor metus non</li>_x000D_
  <li>dapibus sapien</li>_x000D_
  <li>phasellus bibendum tincidunt</li>_x000D_
  <li>quam vitae accumsan</li>_x000D_
  <li>ut interdum eget nisl in eleifend</li>_x000D_
  <li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
_x000D_
_x000D_

I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc(), or CSS preprocessors which only work when the units are the same, etc.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

Simple explanation about what a Index out of bound exception is:

Just think one train is there its compartments are D1,D2,D3. One passenger came to enter the train and he have the ticket for D4. now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.

Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0] and array[1] are existing. If we try to access array[3], it's not there actually, so an index out of bound exception will arise.

How to catch all exceptions in c# using try and catch?

Both ways are correct.

If you need to do something with the Exception object in the catch block then you should use

try {
    // code....
}
catch (Exception ex){}

and then use ex in the catch block.

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

List of phone number country codes

You can easily convert to xml format using online converters:

I have converted the list:

<?xml version="1.0" encoding="UTF-8" ?>
<countries>
    <code>+7 840</code>
    <name>Abkhazia</name>
</countries>
<countries>
    <code>+93</code>
    <name>Afghanistan</name>
</countries>
<countries>
    <code>+355</code>
    <name>Albania</name>
</countries>
<countries>
    <code>+213</code>
    <name>Algeria</name>
</countries>
<countries>
    <code>+1 684</code>
    <name>American Samoa</name>
</countries>
<countries>
    <code>+376</code>
    <name>Andorra</name>
</countries>
<countries>
    <code>+244</code>
    <name>Angola</name>
</countries>
<countries>
    <code>+1 264</code>
    <name>Anguilla</name>
</countries>
<countries>
    <code>+1 268</code>
    <name>Antigua and Barbuda</name>
</countries>
<countries>
    <code>+54</code>
    <name>Argentina</name>
</countries>
<countries>
    <code>+374</code>
    <name>Armenia</name>
</countries>
<countries>
    <code>+297</code>
    <name>Aruba</name>
</countries>
<countries>
    <code>+247</code>
    <name>Ascension</name>
</countries>
<countries>
    <code>+61</code>
    <name>Australia</name>
</countries>
<countries>
    <code>+672</code>
    <name>Australian External Territories</name>
</countries>
<countries>
    <code>+43</code>
    <name>Austria</name>
</countries>
<countries>
    <code>+994</code>
    <name>Azerbaijan</name>
</countries>
<countries>
    <code>+1 242</code>
    <name>Bahamas</name>
</countries>
<countries>
    <code>+973</code>
    <name>Bahrain</name>
</countries>
<countries>
    <code>+880</code>
    <name>Bangladesh</name>
</countries>
<countries>
    <code>+1 246</code>
    <name>Barbados</name>
</countries>
<countries>
    <code>+1 268</code>
    <name>Barbuda</name>
</countries>
<countries>
    <code>+375</code>
    <name>Belarus</name>
</countries>
<countries>
    <code>+32</code>
    <name>Belgium</name>
</countries>
<countries>
    <code>+501</code>
    <name>Belize</name>
</countries>
<countries>
    <code>+229</code>
    <name>Benin</name>
</countries>
<countries>
    <code>+1 441</code>
    <name>Bermuda</name>
</countries>
<countries>
    <code>+975</code>
    <name>Bhutan</name>
</countries>
<countries>
    <code>+591</code>
    <name>Bolivia</name>
</countries>
<countries>
    <code>+387</code>
    <name>Bosnia and Herzegovina</name>
</countries>
<countries>
    <code>+267</code>
    <name>Botswana</name>
</countries>
<countries>
    <code>+55</code>
    <name>Brazil</name>
</countries>
<countries>
    <code>+246</code>
    <name>British Indian Ocean Territory</name>
</countries>
<countries>
    <code>+1 284</code>
    <name>British Virgin Islands</name>
</countries>
<countries>
    <code>+673</code>
    <name>Brunei</name>
</countries>
<countries>
    <code>+359</code>
    <name>Bulgaria</name>
</countries>
<countries>
    <code>+226</code>
    <name>Burkina Faso</name>
</countries>
<countries>
    <code>+257</code>
    <name>Burundi</name>
</countries>
<countries>
    <code>+855</code>
    <name>Cambodia</name>
</countries>
<countries>
    <code>+237</code>
    <name>Cameroon</name>
</countries>
<countries>
    <code>+1</code>
    <name>Canada</name>
</countries>
<countries>
    <code>+238</code>
    <name>Cape Verde</name>
</countries>
<countries>
    <code>+ 345</code>
    <name>Cayman Islands</name>
</countries>
<countries>
    <code>+236</code>
    <name>Central African Republic</name>
</countries>
<countries>
    <code>+235</code>
    <name>Chad</name>
</countries>
<countries>
    <code>+56</code>
    <name>Chile</name>
</countries>
<countries>
    <code>+86</code>
    <name>China</name>
</countries>
<countries>
    <code>+61</code>
    <name>Christmas Island</name>
</countries>
<countries>
    <code>+61</code>
    <name>Cocos-Keeling Islands</name>
</countries>
<countries>
    <code>+57</code>
    <name>Colombia</name>
</countries>
<countries>
    <code>+269</code>
    <name>Comoros</name>
</countries>
<countries>
    <code>+242</code>
    <name>Congo</name>
</countries>
<countries>
    <code>+243</code>
    <name>Congo, Dem. Rep. of (Zaire)</name>
</countries>
<countries>
    <code>+682</code>
    <name>Cook Islands</name>
</countries>
<countries>
    <code>+506</code>
    <name>Costa Rica</name>
</countries>
<countries>
    <code>+385</code>
    <name>Croatia</name>
</countries>
<countries>
    <code>+53</code>
    <name>Cuba</name>
</countries>
<countries>
    <code>+599</code>
    <name>Curacao</name>
</countries>
<countries>
    <code>+537</code>
    <name>Cyprus</name>
</countries>
<countries>
    <code>+420</code>
    <name>Czech Republic</name>
</countries>
<countries>
    <code>+45</code>
    <name>Denmark</name>
</countries>
<countries>
    <code>+246</code>
    <name>Diego Garcia</name>
</countries>
<countries>
    <code>+253</code>
    <name>Djibouti</name>
</countries>
<countries>
    <code>+1 767</code>
    <name>Dominica</name>
</countries>
<countries>
    <code>+1 809</code>
    <name>Dominican Republic</name>
</countries>
<countries>
    <code>+670</code>
    <name>East Timor</name>
</countries>
<countries>
    <code>+56</code>
    <name>Easter Island</name>
</countries>
<countries>
    <code>+593</code>
    <name>Ecuador</name>
</countries>
<countries>
    <code>+20</code>
    <name>Egypt</name>
</countries>
<countries>
    <code>+503</code>
    <name>El Salvador</name>
</countries>
<countries>
    <code>+240</code>
    <name>Equatorial Guinea</name>
</countries>
<countries>
    <code>+291</code>
    <name>Eritrea</name>
</countries>
<countries>
    <code>+372</code>
    <name>Estonia</name>
</countries>
<countries>
    <code>+251</code>
    <name>Ethiopia</name>
</countries>
<countries>
    <code>+500</code>
    <name>Falkland Islands</name>
</countries>
<countries>
    <code>+298</code>
    <name>Faroe Islands</name>
</countries>
<countries>
    <code>+679</code>
    <name>Fiji</name>
</countries>
<countries>
    <code>+358</code>
    <name>Finland</name>
</countries>
<countries>
    <code>+33</code>
    <name>France</name>
</countries>
<countries>
    <code>+596</code>
    <name>French Antilles</name>
</countries>
<countries>
    <code>+594</code>
    <name>French Guiana</name>
</countries>
<countries>
    <code>+689</code>
    <name>French Polynesia</name>
</countries>
<countries>
    <code>+241</code>
    <name>Gabon</name>
</countries>
<countries>
    <code>+220</code>
    <name>Gambia</name>
</countries>
<countries>
    <code>+995</code>
    <name>Georgia</name>
</countries>
<countries>
    <code>+49</code>
    <name>Germany</name>
</countries>
<countries>
    <code>+233</code>
    <name>Ghana</name>
</countries>
<countries>
    <code>+350</code>
    <name>Gibraltar</name>
</countries>
<countries>
    <code>+30</code>
    <name>Greece</name>
</countries>
<countries>
    <code>+299</code>
    <name>Greenland</name>
</countries>
<countries>
    <code>+1 473</code>
    <name>Grenada</name>
</countries>
<countries>
    <code>+590</code>
    <name>Guadeloupe</name>
</countries>
<countries>
    <code>+1 671</code>
    <name>Guam</name>
</countries>
<countries>
    <code>+502</code>
    <name>Guatemala</name>
</countries>
<countries>
    <code>+224</code>
    <name>Guinea</name>
</countries>
<countries>
    <code>+245</code>
    <name>Guinea-Bissau</name>
</countries>
<countries>
    <code>+595</code>
    <name>Guyana</name>
</countries>
<countries>
    <code>+509</code>
    <name>Haiti</name>
</countries>
<countries>
    <code>+504</code>
    <name>Honduras</name>
</countries>
<countries>
    <code>+852</code>
    <name>Hong Kong SAR China</name>
</countries>
<countries>
    <code>+36</code>
    <name>Hungary</name>
</countries>
<countries>
    <code>+354</code>
    <name>Iceland</name>
</countries>
<countries>
    <code>+91</code>
    <name>India</name>
</countries>
<countries>
    <code>+62</code>
    <name>Indonesia</name>
</countries>
<countries>
    <code>+98</code>
    <name>Iran</name>
</countries>
<countries>
    <code>+964</code>
    <name>Iraq</name>
</countries>
<countries>
    <code>+353</code>
    <name>Ireland</name>
</countries>
<countries>
    <code>+972</code>
    <name>Israel</name>
</countries>
<countries>
    <code>+39</code>
    <name>Italy</name>
</countries>
<countries>
    <code>+225</code>
    <name>Ivory Coast</name>
</countries>
<countries>
    <code>+1 876</code>
    <name>Jamaica</name>
</countries>
<countries>
    <code>+81</code>
    <name>Japan</name>
</countries>
<countries>
    <code>+962</code>
    <name>Jordan</name>
</countries>
<countries>
    <code>+7 7</code>
    <name>Kazakhstan</name>
</countries>
<countries>
    <code>+254</code>
    <name>Kenya</name>
</countries>
<countries>
    <code>+686</code>
    <name>Kiribati</name>
</countries>
<countries>
    <code>+965</code>
    <name>Kuwait</name>
</countries>
<countries>
    <code>+996</code>
    <name>Kyrgyzstan</name>
</countries>
<countries>
    <code>+856</code>
    <name>Laos</name>
</countries>
<countries>
    <code>+371</code>
    <name>Latvia</name>
</countries>
<countries>
    <code>+961</code>
    <name>Lebanon</name>
</countries>
<countries>
    <code>+266</code>
    <name>Lesotho</name>
</countries>
<countries>
    <code>+231</code>
    <name>Liberia</name>
</countries>
<countries>
    <code>+218</code>
    <name>Libya</name>
</countries>
<countries>
    <code>+423</code>
    <name>Liechtenstein</name>
</countries>
<countries>
    <code>+370</code>
    <name>Lithuania</name>
</countries>
<countries>
    <code>+352</code>
    <name>Luxembourg</name>
</countries>
<countries>
    <code>+853</code>
    <name>Macau SAR China</name>
</countries>
<countries>
    <code>+389</code>
    <name>Macedonia</name>
</countries>
<countries>
    <code>+261</code>
    <name>Madagascar</name>
</countries>
<countries>
    <code>+265</code>
    <name>Malawi</name>
</countries>
<countries>
    <code>+60</code>
    <name>Malaysia</name>
</countries>
<countries>
    <code>+960</code>
    <name>Maldives</name>
</countries>
<countries>
    <code>+223</code>
    <name>Mali</name>
</countries>
<countries>
    <code>+356</code>
    <name>Malta</name>
</countries>
<countries>
    <code>+692</code>
    <name>Marshall Islands</name>
</countries>
<countries>
    <code>+596</code>
    <name>Martinique</name>
</countries>
<countries>
    <code>+222</code>
    <name>Mauritania</name>
</countries>
<countries>
    <code>+230</code>
    <name>Mauritius</name>
</countries>
<countries>
    <code>+262</code>
    <name>Mayotte</name>
</countries>
<countries>
    <code>+52</code>
    <name>Mexico</name>
</countries>
<countries>
    <code>+691</code>
    <name>Micronesia</name>
</countries>
<countries>
    <code>+1 808</code>
    <name>Midway Island</name>
</countries>
<countries>
    <code>+373</code>
    <name>Moldova</name>
</countries>
<countries>
    <code>+377</code>
    <name>Monaco</name>
</countries>
<countries>
    <code>+976</code>
    <name>Mongolia</name>
</countries>
<countries>
    <code>+382</code>
    <name>Montenegro</name>
</countries>
<countries>
    <code>+1664</code>
    <name>Montserrat</name>
</countries>
<countries>
    <code>+212</code>
    <name>Morocco</name>
</countries>
<countries>
    <code>+95</code>
    <name>Myanmar</name>
</countries>
<countries>
    <code>+264</code>
    <name>Namibia</name>
</countries>
<countries>
    <code>+674</code>
    <name>Nauru</name>
</countries>
<countries>
    <code>+977</code>
    <name>Nepal</name>
</countries>
<countries>
    <code>+31</code>
    <name>Netherlands</name>
</countries>
<countries>
    <code>+599</code>
    <name>Netherlands Antilles</name>
</countries>
<countries>
    <code>+1 869</code>
    <name>Nevis</name>
</countries>
<countries>
    <code>+687</code>
    <name>New Caledonia</name>
</countries>
<countries>
    <code>+64</code>
    <name>New Zealand</name>
</countries>
<countries>
    <code>+505</code>
    <name>Nicaragua</name>
</countries>
<countries>
    <code>+227</code>
    <name>Niger</name>
</countries>
<countries>
    <code>+234</code>
    <name>Nigeria</name>
</countries>
<countries>
    <code>+683</code>
    <name>Niue</name>
</countries>
<countries>
    <code>+672</code>
    <name>Norfolk Island</name>
</countries>
<countries>
    <code>+850</code>
    <name>North Korea</name>
</countries>
<countries>
    <code>+1 670</code>
    <name>Northern Mariana Islands</name>
</countries>
<countries>
    <code>+47</code>
    <name>Norway</name>
</countries>
<countries>
    <code>+968</code>
    <name>Oman</name>
</countries>
<countries>
    <code>+92</code>
    <name>Pakistan</name>
</countries>
<countries>
    <code>+680</code>
    <name>Palau</name>
</countries>
<countries>
    <code>+970</code>
    <name>Palestinian Territory</name>
</countries>
<countries>
    <code>+507</code>
    <name>Panama</name>
</countries>
<countries>
    <code>+675</code>
    <name>Papua New Guinea</name>
</countries>
<countries>
    <code>+595</code>
    <name>Paraguay</name>
</countries>
<countries>
    <code>+51</code>
    <name>Peru</name>
</countries>
<countries>
    <code>+63</code>
    <name>Philippines</name>
</countries>
<countries>
    <code>+48</code>
    <name>Poland</name>
</countries>
<countries>
    <code>+351</code>
    <name>Portugal</name>
</countries>
<countries>
    <code>+1 787</code>
    <name>Puerto Rico</name>
</countries>
<countries>
    <code>+974</code>
    <name>Qatar</name>
</countries>
<countries>
    <code>+262</code>
    <name>Reunion</name>
</countries>
<countries>
    <code>+40</code>
    <name>Romania</name>
</countries>
<countries>
    <code>+7</code>
    <name>Russia</name>
</countries>
<countries>
    <code>+250</code>
    <name>Rwanda</name>
</countries>
<countries>
    <code>+685</code>
    <name>Samoa</name>
</countries>
<countries>
    <code>+378</code>
    <name>San Marino</name>
</countries>
<countries>
    <code>+966</code>
    <name>Saudi Arabia</name>
</countries>
<countries>
    <code>+221</code>
    <name>Senegal</name>
</countries>
<countries>
    <code>+381</code>
    <name>Serbia</name>
</countries>
<countries>
    <code>+248</code>
    <name>Seychelles</name>
</countries>
<countries>
    <code>+232</code>
    <name>Sierra Leone</name>
</countries>
<countries>
    <code>+65</code>
    <name>Singapore</name>
</countries>
<countries>
    <code>+421</code>
    <name>Slovakia</name>
</countries>
<countries>
    <code>+386</code>
    <name>Slovenia</name>
</countries>
<countries>
    <code>+677</code>
    <name>Solomon Islands</name>
</countries>
<countries>
    <code>+27</code>
    <name>South Africa</name>
</countries>
<countries>
    <code>+500</code>
    <name>South Georgia and the South Sandwich Islands</name>
</countries>
<countries>
    <code>+82</code>
    <name>South Korea</name>
</countries>
<countries>
    <code>+34</code>
    <name>Spain</name>
</countries>
<countries>
    <code>+94</code>
    <name>Sri Lanka</name>
</countries>
<countries>
    <code>+249</code>
    <name>Sudan</name>
</countries>
<countries>
    <code>+597</code>
    <name>Suriname</name>
</countries>
<countries>
    <code>+268</code>
    <name>Swaziland</name>
</countries>
<countries>
    <code>+46</code>
    <name>Sweden</name>
</countries>
<countries>
    <code>+41</code>
    <name>Switzerland</name>
</countries>
<countries>
    <code>+963</code>
    <name>Syria</name>
</countries>
<countries>
    <code>+886</code>
    <name>Taiwan</name>
</countries>
<countries>
    <code>+992</code>
    <name>Tajikistan</name>
</countries>
<countries>
    <code>+255</code>
    <name>Tanzania</name>
</countries>
<countries>
    <code>+66</code>
    <name>Thailand</name>
</countries>
<countries>
    <code>+670</code>
    <name>Timor Leste</name>
</countries>
<countries>
    <code>+228</code>
    <name>Togo</name>
</countries>
<countries>
    <code>+690</code>
    <name>Tokelau</name>
</countries>
<countries>
    <code>+676</code>
    <name>Tonga</name>
</countries>
<countries>
    <code>+1 868</code>
    <name>Trinidad and Tobago</name>
</countries>
<countries>
    <code>+216</code>
    <name>Tunisia</name>
</countries>
<countries>
    <code>+90</code>
    <name>Turkey</name>
</countries>
<countries>
    <code>+993</code>
    <name>Turkmenistan</name>
</countries>
<countries>
    <code>+1 649</code>
    <name>Turks and Caicos Islands</name>
</countries>
<countries>
    <code>+688</code>
    <name>Tuvalu</name>
</countries>
<countries>
    <code>+1 340</code>
    <name>U.S. Virgin Islands</name>
</countries>
<countries>
    <code>+256</code>
    <name>Uganda</name>
</countries>
<countries>
    <code>+380</code>
    <name>Ukraine</name>
</countries>
<countries>
    <code>+971</code>
    <name>United Arab Emirates</name>
</countries>
<countries>
    <code>+44</code>
    <name>United Kingdom</name>
</countries>
<countries>
    <code>+1</code>
    <name>United States</name>
</countries>
<countries>
    <code>+598</code>
    <name>Uruguay</name>
</countries>
<countries>
    <code>+998</code>
    <name>Uzbekistan</name>
</countries>
<countries>
    <code>+678</code>
    <name>Vanuatu</name>
</countries>
<countries>
    <code>+58</code>
    <name>Venezuela</name>
</countries>
<countries>
    <code>+84</code>
    <name>Vietnam</name>
</countries>
<countries>
    <code>+1 808</code>
    <name>Wake Island</name>
</countries>
<countries>
    <code>+681</code>
    <name>Wallis and Futuna</name>
</countries>
<countries>
    <code>+967</code>
    <name>Yemen</name>
</countries>
<countries>
    <code>+260</code>
    <name>Zambia</name>
</countries>
<countries>
    <code>+255</code>
    <name>Zanzibar</name>
</countries>
<countries>
    <code>+263</code>
    <name>Zimbabwe</name>
</countries>

Why is AJAX returning HTTP status code 0?

Status code 0 means the requested url is not reachable. By changing http://something/something to https://something/something worked for me. IE throwns an error saying "permission denied" when the status code is 0, other browsers dont.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

Listing available com ports with Python

Basically mentioned this in pyserial documentation https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports

import serial.tools.list_ports
ports = serial.tools.list_ports.comports()

for port, desc, hwid in sorted(ports):
        print("{}: {} [{}]".format(port, desc, hwid))

Result :

COM1: Communications Port (COM1) [ACPI\PNP0501\1]

COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]

Regex number between 1 and 100

For integers from 1 to 100 with no preceding 0 try:

^[1-9]$|^[1-9][0-9]$|^(100)$

For integers from 0 to 100 with no preceding 0 try:

^[0-9]$|^[1-9][0-9]$|^(100)$

Regards

How do I scroll to an element using JavaScript?

You can use an anchor to "focus" the div. I.e:

<div id="myDiv"></div>

and then use the following javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

MySQL equivalent of DECODE function in Oracle

The example translates directly to:

Select Name, CASE Age
       WHEN 13 then 'Thirteen' WHEN 14 then 'Fourteen' WHEN 15 then 'Fifteen' WHEN 16 then 'Sixteen'
       WHEN 17 then 'Seventeen' WHEN 18 then 'Eighteen' WHEN 19 then 'Nineteen'
       ELSE 'Adult' END AS AgeBracket
FROM Person

which you may prefer to format e.g. like this:

Select Name,
       CASE Age
         when 13 then 'Thirteen'
         when 14 then 'Fourteen'
         when 15 then 'Fifteen'
         when 16 then 'Sixteen'
         when 17 then 'Seventeen'
         when 18 then 'Eighteen'
         when 19 then 'Nineteen'
         else         'Adult'
       END AS AgeBracket
FROM Person

How to download an entire directory and subdirectories using wget?

This will help

wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir

Initializing a two dimensional std::vector

The general syntax, as depicted already is:

std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))  

Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.

Also it can be written like this:

std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)

Inputting values in a 2-D vector is similar to inputting values in a 2-D array:

for(int i = 0; i < A_NUMBER; i++) {
     for(int j = 0; j < OTHER_NUMBER; j++) {
         std::cin >> v[i][j]
     }
}

Examples have already been stated in other answers....!

How to make div background color transparent in CSS

It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/

HTML:

   <button id="toggle-box">toggle</button>
   <div id="box" style="display:none;" ><img src="x"></div>
   <button id="toggle-box2">toggle</button>
   <div id="box2" style="display:none;"><img src="xx"></div>
   <button id="toggle-box3">toggle</button>
   <div id="box3" style="display:none;" ><img src="xxx"></div>

CSS:

#box {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:1;
}
#box2 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
      #box3 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
 body {background-color:#c0c0c0; }

JS:

$('#toggle-box').click().toggle(function() {
$('#box').animate({ width: 'show' });
}, function() {
$('#box').animate({ width: 'hide' });
});

$('#toggle-box2').click().toggle(function() {
$('#box2').animate({ width: 'show' });
}, function() {
$('#box2').animate({ width: 'hide' });
});
$('#toggle-box3').click().toggle(function() {
$('#box3').animate({ width: 'show' });
 }, function() {
$('#box3').animate({ width: 'hide' });
});

And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

Spring schemaLocation fails when there is no internet connection

We solved the problem doing this:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false); // This avoid to search schema online
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "TransactionMessage_v1.0.xsd");

Please note that our application is a Java standalone offline app.

How to use the ConfigurationManager.AppSettings

you should use []

var x = ConfigurationManager.AppSettings["APIKey"];

What is the difference between a strongly typed language and a statically typed language?

Data Coercion does not necessarily mean weakly typed because sometimes its syntacical sugar:

The example above of Java being weakly typed because of

String s = "abc" + 123;

Is not weakly typed example because its really doing:

String s = "abc" + new Integer(123).toString()

Data coercion is also not weakly typed if you are constructing a new object. Java is a very bad example of weakly typed (and any language that has good reflection will most likely not be weakly typed). Because the runtime of the language always knows what the type is (the exception might be native types).

This is unlike C. C is the one of the best examples of weakly typed. The runtime has no idea if 4 bytes is an integer, a struct, a pointer or a 4 characters.

The runtime of the language really defines whether or not its weakly typed otherwise its really just opinion.

EDIT: After further thought this is not necessarily true as the runtime does not have to have all the types reified in the runtime system to be a Strongly Typed system. Haskell and ML have such complete static analysis that they can potential ommit type information from the runtime.

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Bootstrap 4: Multilevel Dropdown Inside Navigation

Using official HTML without adding extra CSS styles and classes, it's like native support.

Just add the following code:

$.fn.dropdown = (function() {
    var $bsDropdown = $.fn.dropdown;
    return function(config) {
        if (typeof config === 'string' && config === 'toggle') { // dropdown toggle trigged
            $('.has-child-dropdown-show').removeClass('has-child-dropdown-show');
            $(this).closest('.dropdown').parents('.dropdown').addClass('has-child-dropdown-show');
        }
        var ret = $bsDropdown.call($(this), config);
        $(this).off('click.bs.dropdown'); // Turn off dropdown.js click event, it will call 'this.toggle()' internal
        return ret;
    }
})();

$(function() {
    $('.dropdown [data-toggle="dropdown"]').on('click', function(e) {
        $(this).dropdown('toggle');
        e.stopPropagation();
    });
    $('.dropdown').on('hide.bs.dropdown', function(e) {
        if ($(this).is('.has-child-dropdown-show')) {
            $(this).removeClass('has-child-dropdown-show');
            e.preventDefault();
        }
        e.stopPropagation();
    });
});

Dropdown of bootstrap can be easily changed to infinite level. It's a pity that they didn't do it.

BTW, a hover version: https://github.com/dallaslu/bootstrap-4-multi-level-dropdown

Here is a perfect demo: https://jsfiddle.net/dallaslu/adky6jvs/ (works well with Bootstrap v4.4.1)

Node.js: get path from the request

req.protocol + '://' + req.get('host') + req.originalUrl

or

req.protocol + '://' + req.headers.host + req.originalUrl // I like this one as it survives from proxy server, getting the original host name

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

Trim whitespace from a String

Using a regex

#include <regex>
#include <string>

string trim(string s) {
    regex e("^\\s+|\\s+$");   // remove leading and trailing spaces
    return regex_replace(s, e, "");
}

Credit to: https://www.regular-expressions.info/examples.html for the regex

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

Adding my solution for this issue for anyone it might help.

I had a ClickOnce solution throwing this error. The app referenced a common "Libs" folder and contained a project reference to a Foo.dll. While none of the projects in the solution referenced the static copy of the Foo.dll in the "Libs" folder, some of the references in that folder did (ie: my solution had refs to Libs\Bar.dll which referenced Foo.dll.) Since the CO app pulled all the dependencies from Libs as well as their dependencies, both copies were going into the project. This was generating the error above.

I fixed the problem by moving my Libs\Foo.dll static version into a subfolder, Libs\Fix\Foo.dll. This change made the ClickOnce app use only the project version of the DLL and the error disappeared.

pandas dataframe groupby datetime month

One solution which avoids MultiIndex is to create a new datetime column setting day = 1. Then group by this column.

Normalise day of month

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

Then use groupby as normal:

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

Comparison with pd.Grouper

The subtle benefit of this solution is, unlike pd.Grouper, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group:

some_group = g.get_group('2017-10-01')

Calculating the last day of October is slightly more cumbersome. pd.Grouper, as of v0.23, does support a convention parameter, but this is only applicable for a PeriodIndex grouper.

Comparison with string conversion

An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX to string '2017-10'. However, this is not recommended since you lose all the efficiency benefits of a datetime series (stored internally as numerical data in a contiguous memory block) versus an object series of strings (stored as an array of pointers).

How to divide flask app into multiple py files?

Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.

I created a Gist with the code for doing this:

https://gist.github.com/Jaza/61f879f577bc9d06029e

As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:

https://github.com/mitsuhiko/flask/issues/593

Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.

Display text on MouseOver for image in html

You can do like this also:

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>

In javascript:

function somefunction()
{
  //Do somethisg.
}

?

What are .NET Assemblies?

In .NET, when we compile our source code then assembly gets generated in Visual Studio. Assembly consists of two parts Manifest and IL(Intermediate Language). Manifest contains assembly metadata means assembly's version requirements, security identity, names and hashes of all files that make up the assembly. IL contains information about classes, constructors, main method etc.

What is the difference between IEnumerator and IEnumerable?

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

Status 301 means that the resource (page) is moved permanently to a new location. The client/browser should not attempt to request the original location but use the new location from now on.

Status 302 means that the resource is temporarily located somewhere else, and the client/browser should continue requesting the original url.

How to create a localhost server to run an AngularJS project

"Assuming that you have nodejs installed",

mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000 in your project directory And boom! you created a server on port 3000 now go check http://localhost:3000

Note: specifying a port is not required you can simply run mini-http or mh to start the server

How to concat string + i?

Try the following:

for i = 1:4
    result = strcat('f',int2str(i));
end

If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning:

filename = strcat('c:\...\name',int2str(i),'.png'); 

Count number of rows by group using dplyr

Another option, not necesarily more elegant, but does not require to refer to a specific column:

mtcars %>% 
  group_by(cyl, gear) %>%
  do(data.frame(nrow=nrow(.)))

show distinct column values in pyspark dataframe: python

If you want to see the distinct values of a specific column in your dataframe , you would just need to write -

    df.select('colname').distinct().show(100,False)

This would show the 100 distinct values (if 100 values are available) for the colname column in the df dataframe.

If you want to do something fancy on the distinct values, you can save the distinct values in a vector

    a = df.select('colname').distinct()

Here, a would have all the distinct values of the column colname

Get number of digits with JavaScript

Please use the following expression to get the length of the number.

length = variableName.toString().length

UIImageView - How to get the file name of the image assigned?

There is no native way to do this; however, you could easily create this behavior yourself.

You can subclass UIImageView and add a new instance variable:

NSString* imageFileName;

Then you could override setImage, first setting imageFileName to the filename of the image you're setting, and then calling [super setImage:imageFileName]. Something like this:

-(void) setImage:(NSString*)fileName
{
   imageFileName = fileName;
   [super setImage:fileName];
}

Just because it can't be done natively doesn't mean it isn't possible :)

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

How to remove all the occurrences of a char in c++ string

In case you have a predicate and/or a non empty output to fill with the filtered string, I would consider:

output.reserve(str.size() + output.size());  
std::copy_if(str.cbegin(), 
             str.cend(), 
             std::back_inserter(output), 
             predicate});

In the original question the predicate is [](char c){return c != 'a';}

JavaScript: clone a function

function cloneFunction(Func, ...args) {
  function newThat(...args2) {
    return new Func(...args2);
  }
  function clone() {
    if (this instanceof clone) {
      return newThat(...args);
    }
    return Func.apply(this, args);
  }
  for (const key in Func) {
    if (Func.hasOwnProperty(key)) {
      clone[key] = Func[key];
    }
  }
  Object.defineProperty(clone, 'name', { value: Func.name, configurable: true })
  return clone
};

function myFunction() {
  console.log('Called Function')
}

myFunction.value = 'something';

const newFunction = cloneFunction(myFunction);

newFunction.another = 'somethingelse';

console.log('Equal? ', newFunction === myFunction);
console.log('Names: ', myFunction.name, newFunction.name);
console.log(myFunction);
console.log(newFunction);
console.log('InstanceOf? ', newFunction instanceof myFunction);

myFunction();
newFunction();

While I would never recommend using this, I thought it would be an interesting little challenge to come up with a more precise clone by taking some of the practices that seemed to be the best and fixing it up a bit. Heres the result of the logs:

Equal?  false
Names:  myFunction myFunction
{ [Function: myFunction] value: 'something' }
{ [Function: myFunction] value: 'something', another: 'somethingelse' }
InstanceOf?  false
Called Function
Called Function

How to read files from resources folder in Scala?

The required file can be accessed as below from resource folder in scala

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString

Generate pdf from HTML in div using Javascript

If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget.

It is done by extending the configuration like this:

...
exportOptions: {
    proxy: "/filesaver/save",
    pdf: {
        fileName: "shieldui-export",
        author: "John Smith",
        dataSource: {
            data: gridData
        },
        readDataSource: true,
        header: {
            cells: [
                { field: "id", title: "ID", width: 50 },
                { field: "name", title: "Person Name", width: 100 },
                { field: "company", title: "Company Name", width: 100 },
                { field: "email", title: "Email Address" }
            ]
        }
    }
}
...

Unable to copy a file from obj\Debug to bin\Debug

If this error was encountered, you can proceed as the following

  1. End the msbuild.exe task
  2. End the explorer.exe task
  3. Run the explorer.exe task again

Python: BeautifulSoup - get an attribute value based on the name attribute

6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:

<span property="addressLocality">Ayr</span>

I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.

How I managed to do it eventually:

>>> from bs4 import BeautifulSoup as bs

>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}

As it's a dict, you can then also use keys and 'values'

>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']

Hopefully it helps someone else!

Can I use conditional statements with EJS templates (in JMVC)?

For others that stumble on this, you can also use ejs params/props in conditional statements:

recipes.js File:

app.get("/recipes", function(req, res) {
    res.render("recipes.ejs", {
        recipes: recipes
    });
});

recipes.ejs File:

<%if (recipes.length > 0) { %>
// Do something with more than 1 recipe
<% } %>

Checking if an object is null in C#

As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.

Soft hyphen in HTML (<wbr> vs. &shy;)

This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:

(function($) { 
  $.fn.breakWords = function() { 
    this.each(function() { 
      if(this.nodeType !== 1) { return; } 

      if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { 
        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 
        this.runtimeStyle.wordBreak = 'break-all'; 
      } 
      else if(document.createTreeWalker) { 

        //Faster Trim in Javascript, Flagrant Badassery 
        //http://blog.stevenlevithan.com/archives/faster-trim-javascript 

        var trim = function(str) { 
          str = str.replace(/^\s\s*/, ''); 
          var ws = /\s/, 
          i = str.length; 
          while (ws.test(str.charAt(--i))); 
          return str.slice(0, i + 1); 
        }; 

        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 

        //For Opera, Safari, and Firefox 
        var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); 
        var node,s,c = String.fromCharCode('8203'); 
        while (dWalker.nextNode()) { 
          node = dWalker.currentNode; 
          //we need to trim String otherwise Firefox will display 
          //incorect text-indent with space characters 
          s = trim( node.nodeValue ).split('').join(c); 
          node.nodeValue = s; 
        } 
      } 
    }); 

    return this; 
  }; 
})(jQuery); 

Most simple code to populate JTable from ResultSet

With all factors put into consideration, with regard to code architecture using modular programming would work very well and with more simplicity in the code. Write a simple

getData() function @returns a 2D array of the data from the database.

pass this funtion to the constructor of the JTabel() constructor i.e

JTabel myTable = new JTable(getData(),columnsArray);

In this case the second argument: columnsArray is a single dimensional array that has the column names

String[] columns = {{"ID","DataOfBirth","Age","Grade","Marks","RegNumber"}};

pass the JTable object to a JScrollPane then you are done, right after adding the ScrollPane to the container ofcourse

JScrollPane scrollPane = new JScrollPane(myTable);

JFrame myFrame = new JFrame();
myFrame.add(scrollPane);

Here is a sample function getData() that queries the database for the data that later is passed on to the JTable

public String[][] getRecords() {
    try (Connection conect = DriverManager.getConnection("jdbc:mysql://localhost:3306/online_students_registration", "root", "")) {
        Statement stm = conect.createStatement();
        String SELECT_QUERY = "SELECT COUNT(*) FROM medicalrecords ;";
        ResultSet cursor = stm.executeQuery(SELECT_QUERY);
        while (cursor.next()) {
            rows = cursor.getInt("COUNT(*)");
            System.out.println("Table will have " + rows + " Rows");
        }
        System.err.println("Contacts row count is obtained!!");
        if (rows < 1) {
            JOptionPane.showMessageDialog(null, "There is NO DATA");
            //contactsRowsCount = 1;
            //System.out.println("Table rows succefully reset to  " + contactsRowsCount + " Rows");
            dataValues = new String[1][8];
            //dataValues[1][5] = "No Values";

            for (int i = 0; i < 1; i++) {
                for (int j = 0; j < 8; j++) {
                    if (j == 0) {
                        dataValues[i][j] = "No Details Available";
                        System.out.println("" + dataValues);
                    } else {
                        dataValues[i][j] = "...";
                        System.out.println("Contacts" + dataValues[i][j]);
                    }
                }
            }

            System.out.println("Return statement is being executed on 0 rows ");
            //return doctoredDataValues;
        } else if (rows > 0) {

            System.out.println("obtain contacts code is being run under  " + rows + " Rows");
            dataValues = new String[rows][8];    //declare array for contacts table data
            System.out.println("[ Line 1584 ]The dataValues object for the JTable succefully set");

            String SELECT_QUERY_CONTACT = "SELECT * FROM medicalrecords; ";

            //OBTAIN CONTACTS FROM DB WITH REGARD TO CONTACT CATEGORY SPECIFIED
            ResultSet contactsTableCursor = stm.executeQuery(SELECT_QUERY_CONTACT);
            //use iterator-algorithm to insert values into the JTable
            for (int i = 0; contactsTableCursor.next() && i < rows; i++) {
                for (int j = 0; j < 8; j++) {
                    dataValues[i][j] = contactsTableCursor.getString(j + 1);
                    System.out.println("Contacts" + dataValues[i][j]);
                }
            }
        }
        JOptionPane.showMessageDialog(null, "Medical Details Added Succefully!!");
    } catch (SQLException e) {

        JOptionPane.showMessageDialog(null, "Unable to Obtain contacts:Server is Offline(LINE 1568)" + e.getMessage());
    }

    return dataValues;

}

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

Do subclasses inherit private fields?

Memory Layout in Java vis-a-vis inheritance

enter image description here

Padding bits/Alignment and the inclusion of Object Class in the VTABLE is not considered. So the object of the subclass does have a place for the private members of the Super class. However, it cannot be accessed from the subclass's objects...

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If that is all you have changed, you may not have the mysqli driver installed or enabled within your PHP configuration.

Check for its presence using phpinfo(), or in your php.ini file (extension=php_mysqli....).

What should be in my .gitignore for an Android Studio project?

Github maintains useful gitignore items for various kinds of projects. Here is the list of useful gitignore items for android projects.

# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# Intellij
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/libraries

# Keystore files
*.jks

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# Google Services (e.g. APIs or Firebase)
google-services.json

# Freeline
freeline.py
freeline/
freeline_project_description.json

Android Gitignore in github

How to use MD5 in javascript to transmit a password

if you're using php jquery, this might help:

   $.ajax({
        url:'phpmd5file.php',
        data:{'mypassword',mypassword},
        dataType:"json",
        method:"POST",
        success:function(mymd5password){
            alert(mymd5password);
        }
    });

on your phpmd5.php file:

echo json_encode($_POST["mypassword"]);

no jsplugins needed. just use ajax and let php md5() do the job.

How to check if a string is numeric?

public static boolean isNumeric(String string) {
    if (string == null || string.isEmpty()) {
        return false;
    }
    int i = 0;
    int stringLength = string.length();
    if (string.charAt(0) == '-') {
        if (stringLength > 1) {
            i++;
        } else {
            return false;
        }
    }
    if (!Character.isDigit(string.charAt(i))
            || !Character.isDigit(string.charAt(stringLength - 1))) {
        return false;
    }
    i++;
    stringLength--;
    if (i >= stringLength) {
        return true;
    }
    for (; i < stringLength; i++) {
        if (!Character.isDigit(string.charAt(i))
                && string.charAt(i) != '.') {
            return false;
        }
    }
    return true;
}

MySQL: How to add one day to datetime field in query

How about this: 

select * from fab_scheduler where custid = 1334666058 and eventdate = eventdate + INTERVAL 1 DAY

Deploy a project using Git push

Using the post-update file below:

  1. Copy over your .git directory to your web server
  2. On your local copy, modify your .git/config file and add your web server as a remote:

    [remote "production"]
        url = username@webserver:/path/to/htdocs/.git
    
  3. On the server, replace .git/hooks/post-update with file below

  4. Add execute access to the file (again, on the server):

    chmod +x .git/hooks/post-update
    
  5. Now, just locally push to your web server and it should automatically update the working copy:

    git push production
    
#!/bin/sh
#
# This hook does two things:
#
#  1. update the "info" files that allow the list of references to be
#     queries over dumb transports such as http
#
#  2. if this repository looks like it is a non-bare repository, and
#     the checked-out branch is pushed to, then update the working copy.
#     This makes "push" function somewhat similarly to darcs and bzr.
#
# To enable this hook, make this file executable by "chmod +x post-update". 
git-update-server-info 
is_bare=$(git-config --get --bool core.bare) 
if [ -z "$is_bare" ]
then
      # for compatibility's sake, guess
      git_dir_full=$(cd $GIT_DIR; pwd)
      case $git_dir_full in */.git) is_bare=false;; *) is_bare=true;; esac
fi 
update_wc() {
      ref=$1
      echo "Push to checked out branch $ref" >&2
      if [ ! -f $GIT_DIR/logs/HEAD ]
      then
             echo "E:push to non-bare repository requires a HEAD reflog" >&2
             exit 1
      fi
      if (cd $GIT_WORK_TREE; git-diff-files -q --exit-code >/dev/null)
      then
             wc_dirty=0
      else
             echo "W:unstaged changes found in working copy" >&2
             wc_dirty=1
             desc="working copy"
      fi
      if git diff-index --cached HEAD@{1} >/dev/null
      then
             index_dirty=0
      else
             echo "W:uncommitted, staged changes found" >&2
             index_dirty=1
             if [ -n "$desc" ]
             then
                   desc="$desc and index"
             else
                   desc="index"
             fi
      fi
      if [ "$wc_dirty" -ne 0 -o "$index_dirty" -ne 0 ]
      then
             new=$(git rev-parse HEAD)
             echo "W:stashing dirty $desc - see git-stash(1)" >&2
             ( trap 'echo trapped $$; git symbolic-ref HEAD "'"$ref"'"' 2 3 13 15 ERR EXIT
             git-update-ref --no-deref HEAD HEAD@{1}
             cd $GIT_WORK_TREE
             git stash save "dirty $desc before update to $new";
             git-symbolic-ref HEAD "$ref"
             )
      fi 
      # eye candy - show the WC updates :)
      echo "Updating working copy" >&2
      (cd $GIT_WORK_TREE
      git-diff-index -R --name-status HEAD >&2
      git-reset --hard HEAD)
} 
if [ "$is_bare" = "false" ]
then
      active_branch=`git-symbolic-ref HEAD`
      export GIT_DIR=$(cd $GIT_DIR; pwd)
      GIT_WORK_TREE=${GIT_WORK_TREE-..}
      for ref
      do
             if [ "$ref" = "$active_branch" ]
             then
                   update_wc $ref
             fi
      done
fi

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How to check if my string is equal to null?

You have to check with null if(str != null).

jQuery scrollTop not working in Chrome but working in Firefox

I have used this with success in Chrome, Firefox, and Safari. Haven't been able to test it in IE yet.

if($(document).scrollTop() !=0){
    $('html, body').animate({ scrollTop: 0 }, 'fast');
}

The reason for the "if" statement is to check if the user is all ready at the top of the site. If so, don't do the animation. That way we don't have to worry so much about screen resolution.

The reason I use $(document).scrollTop instead of ie. $('html,body') is cause Chrome always return 0 for some reason.

Is there a combination of "LIKE" and "IN" in SQL?

I may have a solution for this, although it will only work in SQL Server 2008 as far as I know. I discovered that you can use the row-constructor described in https://stackoverflow.com/a/7285095/894974 to join a 'fictional' table using a like clause. It sounds more complex then it is, look:

SELECT [name]
  ,[userID]
  ,[name]
  ,[town]
  ,[email]
FROM usr
join (values ('hotmail'),('gmail'),('live')) as myTable(myColumn) on email like '%'+myTable.myColumn+'%' 

This will result in all users with an e-mail adres like the ones provided in the list. Hope it's of use to anyone. The problem had been bothering me a while.

Regex for numbers only

While non of the above solutions was fitting my purpose, this worked for me.

var pattern = @"^(-?[1-9]+\d*([.]\d+)?)$|^(-?0[.]\d*[1-9]+)$|^0$|^0.0$";
return Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;

Example of valid values: "3", "-3", "0", "0.0", "1.0", "0.7", "690.7", "0.0001", "-555", "945465464654"

Example of not valid values: "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "--1", "-.1", "-0", "00099", "099"

Script for rebuilding and reindexing the fragmented index?

I have found the following script is very good at maintaining indexes, you can have this scheduled to run nightly or whatever other timeframe you wish.

http://sqlfool.com/2011/06/index-defrag-script-v4-1/

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can I remove the decimal part from JavaScript number?

Use Math.round() function.

Math.round(65.98) // will return 66 
Math.round(65.28) // will return 65

Delete the last two characters of the String

Subtract -2 or -3 basis of removing last space also.

 public static void main(String[] args) {
        String s = "apple car 05";
        System.out.println(s.substring(0, s.length() - 2));
    }

Output

apple car

XDocument or XmlDocument

XmlDocument is great for developers who are familiar with the XML DOM object model. It's been around for a while, and more or less corresponds to a W3C standard. It supports manual navigation as well as XPath node selection.

XDocument powers the LINQ to XML feature in .NET 3.5. It makes heavy use of IEnumerable<> and can be easier to work with in straight C#.

Both document models require you to load the entire document into memory (unlike XmlReader for example).

generate days from date range

Alright.. Try this: http://www.devshed.com/c/a/MySQL/Delving-Deeper-into-MySQL-50/
http://dev.mysql.com/doc/refman/5.0/en/loop-statement.html
http://www.roseindia.net/sql/mysql-example/mysql-loop.shtml

Use that to, say, generate a temp table, and then do a select * on the temp table. Or output the results one at a time.
What you say you want to do can't be done with a SELECT statement, but it might be doable with things specific to MySQL.
Then again, maybe you need cursors: http://dev.mysql.com/doc/refman/5.0/en/cursors.html

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

HTML image bottom alignment inside DIV container

This is your code: http://jsfiddle.net/WSFnX/

Using display: table-cell is fine, provided that you're aware that it won't work in IE6/7. Other than that, it's safe: Is there a disadvantage of using `display:table-cell`on divs?

To fix the space at the bottom, add vertical-align: bottom to the actual imgs:

http://jsfiddle.net/WSFnX/1/

Removing the space between the images boils down to this: bikeshedding CSS3 property alternative?

So, here's a demo with the whitespace removed in your HTML: http://jsfiddle.net/WSFnX/4/

Visual Studio 2012 Web Publish doesn't copy files

In Visual Studio 2012, switching between releases still causes problems.

We added a pre-build event to delete the obj folder: del /s /f /q $(ProjectDir)\obj and it fixed the issue of publishing. Cleaning works sometimes, but not always.

How to print multiple variable lines in Java

You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

(WAMP/XAMP) send Mail using SMTP localhost

Here's the steps to achieve this:

  • Download the sendmail.zip through this link

    • Now, extract the folder and put it to C:/wamp/. Make sure that these four files are present: sendmail.exe, libeay32.dll, ssleay32.ddl and sendmail.ini.
    • Open sendmail.ini and set the configuration as follows:

    • smtp_server=smtp.gmail.com

    • smtp_port=465
    • smtp_ssl=ssl
    • default_domain=localhost
    • error_logfile=error.log
    • debug_logfile=debug.log
    • auth_username=[your_gmail_account_username]@gmail.com
    • auth_password=[your_gmail_account_password]
    • pop3_server=
    • pop3_username=
    • pop3_password=
    • force_sender=
    • force_recipient=
    • hostname=localhost

    • Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.

    • Run your WAMP Server. Enable ssl_module under Apache Module.

    • Next, enable php_openssl and php_sockets under PHP.

    • Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP =
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
  • Restart Wamp Server

I hope this will work for you..

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

In my case I solved the problem editing [tomcat]/Catalina/localhost/[mywebapp_name].xml instead of META-INF/context.xml.

Create XML in Javascript

xml-writer(npm package) I think this is the good way to create and write xml file easy. Also it can be used on server side with nodejs.

var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());

Exercises to improve my Java programming skills

Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problems

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

@class vs. #import

My inquiry is this. When does one use #import and when does one use @class?

Simple answer: You #import or #include when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass, struct MONStruct, @protocol MONProtocol).

Here are some common examples of physical dependence:

  • Any C or C++ value (a pointer or reference is not a physical dependency). If you have a CGPoint as an ivar or property, the compiler will need to see the declaration of CGPoint.
  • Your superclass.
  • A method you use.

Sometimes if I use a @class declaration, I see a common compiler warning such as the following: "warning: receiver 'FooController' is a forward class and corresponding @interface may not exist."

The compiler's actually very lenient in this regard. It will drop hints (such as the one above), but you can trash your stack easily if you ignore them and don't #import properly. Although it should (IMO), the compiler does not enforce this. In ARC, the compiler is more strict because it is responsible for reference counting. What happens is the compiler falls back on a default when it encounters an unknown method which you call. Every return value and parameter is assumed to be id. Thus, you ought to eradicate every warning from your codebases because this should be considered physical dependence. This is analogous to calling a C function which is not declared. With C, parameters are assumed to be int.

The reason you would favor forward declarations is that you can reduce your build times by factors because there is minimal dependence. With forward declarations, the compiler sees there is a name, and can correctly parse and compile the program without seeing the class declaration or all of its dependencies when there is no physical dependency. Clean builds take less time. Incremental builds take less time. Sure, you will end up spending a little more time making sure the all the headers you need are visible to every translation as a consequence, but this pays off in reduced build times quickly (assuming your project is not tiny).

If you use #import or #include instead, you're throwing a lot more work at the compiler than is necessary. You're also introducing complex header dependencies. You can liken this to a brute-force algorithm. When you #import, you're dragging in tons of unnecessary information, which requires a lot of memory, disk I/O, and CPU to parse and compile the sources.

ObjC is pretty close to ideal for a C based language with regards to dependency because NSObject types are never values -- NSObject types are always reference counted pointers. So you can get away with incredibly fast compile times if you structure your program's dependencies appropriately and forward where possible because there is very little physical dependence required. You can also declare properties in the class extensions to further minimize dependence. That's a huge bonus for large systems -- you would know the difference it makes if you have ever developed a large C++ codebase.

Therefore, my recommendation is to use forwards where possible, and then to #import where there is physical dependence. If you see the warning or another which implies physical dependence -- fix them all. The fix is to #import in your implementation file.

As you build libraries, you will likely classify some interfaces as a group, in which case you would #import that library where physical dependence is introduced (e.g. #import <AppKit/AppKit.h>). This can introduce dependence, but the library maintainers can often handle the physical dependencies for you as needed -- if they introduce a feature, they can minimize the impact it has on your builds.

How to default to other directory instead of home directory

I use ConEmu (strongly recommended on Windows) where I have a task for starting Git Bash like

enter image description here

Note the button "Startup dir..." in the bottom. It adds a -new_console:d:<path> to the startup command of the Git Bash. Make it point to wherever you like

How to get all Errors from ASP.Net MVC modelState?

Outputting just the Error messages themselves wasn't sufficient for me, but this did the trick.

var modelQuery = (from kvp in ModelState
                  let field = kvp.Key
                  let state = kvp.Value
                  where state.Errors.Count > 0
                  let val = state.Value?.AttemptedValue ?? "[NULL]"

                  let errors = string.Join(";", state.Errors.Select(err => err.ErrorMessage))
                  select string.Format("{0}:[{1}] (ERRORS: {2})", field, val, errors));

Trace.WriteLine(string.Join(Environment.NewLine, modelQuery));

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

Remember that stringToEdit.replaceAll(String, String) returns the result string. It doesn't modify stringToEdit because Strings are immutable in Java. To get any change to stick, you should use

stringToEdit = stringToEdit.replaceAll("'", "\\'");

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

How to get thread id of a pthread in linux c program?

You can also write in this manner and it does the same. For eg:

for(int i=0;i < total; i++)
{
    pthread_join(pth[i],NULL);
    cout << "SUM of thread id " << pth[i] << " is " << args[i].sum << endl;
}

This program sets up an array of pthread_t and calculate sum on each. So it is printing the sum of each thread with thread id.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Perhaps something like this for the first problem, you can simply access the columns by their names:

>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
          b         e
1  0.071146  0.132145
2  0.495152  0.420219

For the second problem:

>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556,  0.13214495],
       [ 0.49515157,  0.42021946]])

How to Apply Gradient to background view of iOS Swift App

Xcode 11 • Swift 5.1


You can design your own Gradient View as follow:

@IBDesignable
public class Gradient: UIView {
    @IBInspectable var startColor:   UIColor = .black { didSet { updateColors() }}
    @IBInspectable var endColor:     UIColor = .white { didSet { updateColors() }}
    @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
    @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
    @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
    @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}

    override public class var layerClass: AnyClass { CAGradientLayer.self }

    var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updatePoints()
        updateLocations()
        updateColors()
    }

}

enter image description here

How do I escape special characters in MySQL?

MySQL has the string function QUOTE, and it should solve this problem:

When to use IMG vs. CSS background-image?

Proper uses of IMG

  1. Use IMG if you intend to have people print your page and you want the image to be included by default. —JayTee
  2. Use IMG (with alt text) when the image has an important semantic meaning, such as a warning icon. This ensures that the meaning of the image can be communicated in all user-agents, including screen readers.

Pragmatic uses of IMG

  1. Use IMG plus alt attribute if the image is part of the content such as a logo or diagram or person (real person, not stock photo people). —sanchothefat
  2. Use IMG if you rely on browser scaling to render an image in proportion to text size.
  3. Use IMG for multiple overlay images in IE6.
  4. Use IMG with a z-index in order to stretch a background image to fill its entire window.
    Note, this is no longer true with CSS3 background-size; see #6 below.
  5. Using img instead of background-image can dramatically improve performance of animations over a background.

When to use CSS background-image

  1. Use CSS background images if the image is not part of the content. —sanchothefat
  2. Use CSS background images when doing image-replacement of text eg. paragraphs/headers. —sanchothefat
  3. Use background-image if you intend to have people print your page and you do not want the image to be included by default. —JayTee
  4. Use background-image if you need to improve download times, as with CSS sprites.
  5. Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
  6. Use background-image with background-size:cover in order to stretch a background image to fill its entire window.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

Will #if RELEASE work like #if DEBUG does in C#?

RELEASE is not defined, but you can use

#if (!DEBUG)
  ...
#endif

python max function using 'key' and lambda expression

How does the max function work?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

What is use of the keyword key in max function? I know it is also used in context of sort function

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Meaning of the lambda expression? How to read them? How do they work?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

How to change language settings in R

If you want to change R's language in terminal to English forever, this works fine for me in macOS:

Open terminal.app, and say:

touch .bash_profile

Then say:

open -a TextEdit.app .bash_profile

These two commands will help you open ".bash_profile" file in TextEdit.

Add this to ".bash_profile" file:

export LANG=en_US.UTF-8

Then save the file, reopen terminal and type R, you will find it's language has changed to english.

If you want language come back to it's original, just simply add a # before export LANG=en_US.UTF-8.

Parenthesis/Brackets Matching using Stack algorithm

Ganesan's answer above is not correct and StackOverflow is not letting me comment or Edit his post. So below is the correct answer. Ganesan has an incorrect facing "[" and is missing the stack isEmpty() check.

The below code will return true if the braces are properly matching.

public static boolean isValidExpression(String expression) {
    Map<Character, Character> openClosePair = new HashMap<Character, Character>();
    openClosePair.put(')', '(');
    openClosePair.put('}', '{');
    openClosePair.put(']', '[');

    Stack<Character> stack = new Stack<Character>();
    for(char ch : expression.toCharArray()) {
        if(openClosePair.containsKey(ch)) {
            if(stack.isEmpty() || stack.pop() != openClosePair.get(ch)) {
                return false;
            }
        } else if(openClosePair.values().contains(ch)) {
            stack.push(ch); 
        }
    }
    return stack.isEmpty();
}

CURRENT_DATE/CURDATE() not working as default DATE value

----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----

Support for DEFAULT with expressions (MDEV-10134).

----- 2018-10-22 8.0.13 General Availability -- -- -----

MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.

How to round an image with Glide library?

its very simple i have seen Glide library its very good library and essay base on volley Google's library

usethis library for rounded image view

https://github.com/hdodenhof/CircleImageView

now

//For a simple view:

 @Override
 public void onCreate(Bundle savedInstanceState) {
  ...

  CircleImageView civProfilePic = (CircleImageView)findViewById(R.id.ivProfile);
  Glide.load("http://goo.gl/h8qOq7").into(civProfilePic);
}

//For a list:

@Override
public View getView(int position, View recycled, ViewGroup container) {
final ImageView myImageView;
 if (recycled == null) {
    myImageView = (CircleImageView) inflater.inflate(R.layout.my_image_view,
            container, false);
} else {
    myImageView = (CircleImageView) recycled;
}

String url = myUrls.get(position);

Glide.load(url)
    .centerCrop()
    .placeholder(R.drawable.loading_spinner)
    .animate(R.anim.fade_in)
    .into(myImageView);

  return myImageView;
}

and in XML

<de.hdodenhof.circleimageview.CircleImageView
   android:id="@+id/ivProfile
   android:layout_width="160dp"
   android:layout_height="160dp"
   android:layout_centerInParent="true"
   android:src="@drawable/hugh"
   app:border_width="2dp"
   app:border_color="@color/dark" />

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

Github permission denied: ssh add agent has no identities

One additional element that I realized is that typically .ssh folder is created in your root folder in Mac OS X /Users/. If you try to use ssh -vT [email protected] from another folder it will give you an error even if you had added the correct key.

You need to add the key again (ssh-add 'correct path to id_rsa') from the current folder to authenticate successfully (assuming that you have already uploaded the key to your profile in Git)

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

Docker: Copying files from Docker container to host

Mount a "volume" and copy the artifacts into there:

mkdir artifacts
docker run -i -v ${PWD}/artifacts:/artifacts ubuntu:14.04 sh << COMMANDS
# ... build software here ...
cp <artifact> /artifacts
# ... copy more artifacts into `/artifacts` ...
COMMANDS

Then when the build finishes and the container is no longer running, it has already copied the artifacts from the build into the artifacts directory on the host.

Edit

Caveat: When you do this, you may run into problems with the user id of the docker user matching the user id of the current running user. That is, the files in /artifacts will be shown as owned by the user with the UID of the user used inside the docker container. A way around this may be to use the calling user's UID:

docker run -i -v ${PWD}:/working_dir -w /working_dir -u $(id -u) \
    ubuntu:14.04 sh << COMMANDS
# Since $(id -u) owns /working_dir, you should be okay running commands here
# and having them work. Then copy stuff into /working_dir/artifacts .
COMMANDS

Chrome: Uncaught SyntaxError: Unexpected end of input

Since it's an async operation the onreadystatechange may happen before the value has loaded in the responseText, try using a window.setTimeout(function () { JSON.parse(xhr.responseText); }, 1000); to see if the error persists? BOL

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

IsNothing versus Is Nothing

I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".

I find this easier to read...

If printDialog IsNot Nothing Then
    'blah
End If

than this...

If Not obj Is Nothing Then
    'blah
End If

set date in input type date

I usually create these two helper functions when using date inputs:

// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
  `${date.getFullYear()
  }-${('0' + (date.getMonth() + 1)).slice(-2)
  }-${('0' + date.getDate()).slice(-2)
  }`;

// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));

You can then set the date input value as:

$('#datePicker').val(dateToInput(new Date()));

And retrieve the selected value like so

const dateVal = inputToDate($('#datePicker').val())

How can I check if PostgreSQL is installed or not via Linux script?

There is no straightforward way to do this. All you can do is check with the package manager (rpm, dpkg) or probe some likely locations for the files you want. Or you could try to connect to a likely port (5432) and see if you get a PostgreSQL protocol response. But none of this is going to be very robust. You might want to review your requirements.

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

The solutions above didn't help me. I've tried 2 first steps from this link. Worked fine for me. But don't forget to

import com.melnykov.fab.FloatingActionButton; 

instead of

import android.support.design.widget.FloatingActionButton;

in your MainActivity.java

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

How does "cat << EOF" work in bash?

This isn't necessarily an answer to the original question, but a sharing of some results from my own testing. This:

<<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

will produce the same file as:

cat <<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

So, I don't see the point of using the cat command.

plot.new has not been called yet

As a newbie, I faced the same 'problem'.

In newbie terms : when you call plot(), the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R. However, some commands, like identify(), act on open/active graph windows. When identify() cannot find an open/active graph window, it gives this error message.

However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify() etc.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

TNS Protocol adapter error while starting Oracle SQL*Plus

Try typing all of this on the command line:

sqlplus / as sysdba

As what you are doing is starting sqlplus and then using sys as sysdba as the user-name which is incorrect as that is not a valid user. By using the above command Oracle is using your system login credentials to access the db. Also, I would confirm that the sqlplus executable you are running is the correct one by checking your path - ensure it is in the bin of the server installation directories.

How to throw RuntimeException ("cannot find symbol")

An Exception is an Object like any other in Java. You need to use the new keyword to create a new Exception before you can throw it.

throw new RuntimeException();

Optionally you could also do the following:

RuntimeException e = new RuntimeException();
throw e;

Both code snippets are equivalent.

Link to the tutorials for completeness.

Swap DIV position with CSS only

The accepted answer worked for most browsers but for some reason on iOS Chrome and Safari browsers the content that should have shown second was being hidden. I tried some other steps that forced content to stack on top of each other, and eventually I tried the following solution that gave me the intended effect (switch content display order on mobile screens), without bugs of stacked or hidden content:

.container {
  display:flex;
  flex-direction: column-reverse;
}

.section1,
.section2 {
  height: auto;
}

Javascript communication between browser tabs/windows

There is also an experimental technology called Broadcast Channel API that is designed specifically for communication between different browser contexts with same origin. You can post messages to and recieve messages from another browser context without having a reference to it:

var channel = new BroadcastChannel("foo");
channel.onmessage = function( e ) {
  // Process messages from other contexts.
};
// Send message to other listening contexts.
channel.postMessage({ value: 42, type: "bar"});

Obviously this is experiental technology and is not supported accross all browsers yet.

How to prevent a file from direct URL Access?

For me this was the only thing that worked and it worked great:

RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@])@@https?://\1/.
RewriteRule .(gif|jpg|jpeg|png|tif|pdf|wav|wmv|wma|avi|mov|mp4|m4v|mp3|zip?)$ - [F]

found it at: https://simplefilelist.com/how-can-i-prevent-direct-url-access-to-my-files-from-outside-my-website/

Contain form within a bootstrap popover?

<a data-title="A Title" data-placement="top" data-html="true" data-content="<form><input type='text'/></form>" data-trigger="hover" rel="popover" class="btn btn-primary" id="test">Top popover</a>

just state data-html="true"

How to remove files from git staging area?

Use "git reset HEAD <file>..." to unstage fils

ex : to unstage all files

git reset HEAD .

to unstage one file

git reset HEAD nameFile.txt

How to get Locale from its String representation in Java?

There doesn't seem to be a static valueOf method for this, which is a bit surprising.

One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales(), comparing their toString values with your value.

Not very nice, but no string parsing required. You could pre-populate a Map of Strings to Locales, and look up your database string in that Map.

Replacing some characters in a string with another character

You might find this link helpful:

http://tldp.org/LDP/abs/html/string-manipulation.html

In general,

To replace the first match of $substring with $replacement:

${string/substring/replacement}

To replace all matches of $substring with $replacement:

${string//substring/replacement}

EDIT: Note that this applies to a variable named $string.

Javascript: best Singleton pattern

function SingletonClass() 
{
    // demo variable
    var names = [];

    // instance of the singleton
    this.singletonInstance = null;

    // Get the instance of the SingletonClass
    // If there is no instance in this.singletonInstance, instanciate one
    var getInstance = function() {
        if (!this.singletonInstance) {
            // create a instance
            this.singletonInstance = createInstance();
        }

        // return the instance of the singletonClass
        return this.singletonInstance;
    }

    // function for the creation of the SingletonClass class
    var createInstance = function() {

        // public methodes
        return {
            add : function(name) {
                names.push(name);
            },
            names : function() {
                return names;
            }
        }
    }

    // wen constructed the getInstance is automaticly called and return the SingletonClass instance 
    return getInstance();
}

var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]

var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]

obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]

How to send email from SQL Server?

Step 1) Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.

Step 2)

RUN:

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

Step 3)

USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'

To loop through the table

DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)

SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]

WHILE @id<=@max_id
BEGIN
    SELECT @email_id=email_id 
    FROM [email_adresses]

    set @query='sp_send_dbmail @profile_name=''yourprofilename'',
                        @recipients='''+@email_id+''',
                        @subject=''Test message'',
                        @body=''This is the body of the test message.
                        Congrates Database Mail Received By you Successfully.'''

    EXEC @query
    SELECT @id=MIN(id) FROM [email_adresses] where id>@id

END

Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

Make sure that the htaccess file is readable by apache:

chmod 644 /var/www/abc/.htaccess 

And make sure the directory it's in is readable and executable:

chmod 755 /var/www/abc/

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
_x000D_
_x000D_

How to find third or n?? maximum salary from salary table?

By subquery:

SELECT salary from
(SELECT rownum ID, EmpSalary salary from
(SELECT DISTINCT EmpSalary from salary_table order by EmpSalary DESC)
where ID = nth)

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

In my case it was because I had another folder that contained xampp and all it's files (htdocs, php e.t.c). Like I installed Xampp twice in different directories and for some reason the configurations of the other one was affecting my current xampp directory and so I had to change the memory size in the php.ini file of the other directory too.

What is the SQL command to return the field names of a table?

MySQL is the same:

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True