Programs & Examples On #Django flatpages

Django flatpages app is a built-in application that allows to store “flat” HTML content in a database and handles the management for you via Django’s admin interface and a Python API.

How to get the EXIF data from a file using C#

Check out this metadata extractor. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.

EDIT metadata-extractor supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.

It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...

var directories = ImageMetadataReader.ReadMetadata(imagePath);

// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
    Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");

// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);

It's available via NuGet and the code's on GitHub.

Array String Declaration


String[] mStrings = new String[title.length];

SQL query for today's date minus two months

Would something like this work for you?


Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height


canvas {  /* or some other selector */
   width: 500px;
   height: 400px;

Or in JavaScript = "500px"; = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;

   return false;

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
<canvas id="c"></canvas>

And Here's a canvas as a float in a paragraph

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_

Here's a canvas in a sizable control panel

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_ = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
body { _x000D_
  margin: 0;_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
pre {_x000D_
  padding: 1em;_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  <div class="slider">_x000D_
  <div class="right">_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
&lt;- drag this_x000D_

here's a canvas as a background

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)


  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

How can I parse a String to BigDecimal?

Try the correct constructor

You can directly instanciate the BigDecimal with the String ;)


BigDecimal bigDecimalValue= new BigDecimal("0.5");

SQL Data Reader - handling Null column values

and / or use ternary operator with assignment:

employee.FirstName = rdr.IsDBNull(indexFirstName))? 
                     String.Empty: rdr.GetString(indexFirstName);

replace the default (when null) value as appropriate for each property type...

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

if (boolean == false) vs. if (!boolean)

The first form, when used with an API that returns Boolean and compared against Boolean.FALSE, will never throw a NullPointerException.

The second form, when used with the java.util.Map interface, also, will never throw a NullPointerException because it returns a boolean and not a Boolean.

If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean that may be NULL.

How to Convert date into MM/DD/YY format in C#


Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Sorting Directory.GetFiles()

If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). You can then sort these using one of the extension methods in System.Linq, e.g.:

DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.

How to view table contents in Mysql Workbench GUI?

After displaying the first 1000 records, you can page through them by clicking on the icon beside "Fetch rows:" in the header of the result grid.

Testing if a site is vulnerable to Sql Injection

SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

First rule of securing any script or page that attaches to a database instance is Do not trust user input.

Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a ' to a paramater, your 'injection' is hoping for the following type of statement:

SELECT username,password FROM users WHERE username='$username'

By appending a ' to that statement, you could then add additional SQL paramaters or queries.: ' OR username --

SELECT username,password FROM users WHERE username='' OR username -- '$username

That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.

Generally there are three types of SQL injection methods:

  • Query Reshaping or redirection (above)
  • Error message based (No such user/password)
  • Blind Injections

Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.


As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.

I want my android application to be only run in portrait mode?

In the manifest, set this for all your activities:

<activity android:name=".YourActivity"

Let me explain:

  • With android:configChanges="orientation" you tell Android that you will be responsible of the changes of orientation.
  • android:screenOrientation="portrait" you set the default orientation mode.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
    //for IE ONLY!

Room persistance library. Delete all

To make use of the Room without abuse of the @Query annotation first use @Query to select all rows and put them in a list, for example:

@Query("SELECT * FROM your_class_table")

List`<`your_class`>` load_all_your_class();

Put his list into the delete annotation, for example:


void deleteAllOfYourTable(List`<`your_class`>` your_class_list);

"message failed to fetch from registry" while trying to install any module

I had this issue with npm v1.1.4 (and node v0.6.12), which are the Ubuntu 12.04 repository versions.

It looks like that version of npm isn't supported any more, updating node (and npm with it) resolved the issue.

First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).

sudo apt-get purge nodejs npm

Then enable nodesource's repo and install:

curl -sL | sudo bash -
sudo apt-get install -y nodejs

Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:

From: here

check if directory exists and delete in one command unix


bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

How to do URL decoding in Java?

I use apache commons

String decodedUrl = new URLCodec().decode(url);

The default charset is UTF-8

Evaluate list.contains string in JSTL

Another way of doing this is using a Map (HashMap) with Key, Value pairs representing your object.

Map<Long, Object> map = new HashMap<Long, Object>();
map.put(new Long(1), "one");
map.put(new Long(2), "two");


<c:if test="${not empty map[1]}">

This should return true if the pair exist in the map

How to extend a class in python?


import color

class Color(color.Color):

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):

This is not necessary in Python 3.x.

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Are global variables bad?

In web applications within an enterprize can be used for holding session/window/thread/user specific data on the server for reasons of optimization and to preserve against loss of work where connection are unstable. As mentioned, race conditions need to be handled. We use a single instance of a class for this information and it is carefully managed.

What are the applications of binary trees?

Implementations of java.util.Set

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

MVC 4 @Scripts "does not exist"

For me this solved the problem, in NuGet package manager console write following:

update-package microsoft.aspnet.mvc -reinstall

phpMyAdmin says no privilege to create database, despite logged in as root user

login in the terminal as a root and execute this command:


Type n in order to not change root password and hit enter, then type y to remove anonymous users and hit enter. Type n if you want to disallow root login remotely and hit enter. Now type y to remove test tables and databases and hit enter, then type y again and hit enter.

and you are good to go :)

Android Fragment onClick button Method

Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).

public class FragName extends Fragment implements View.OnClickListener { 
    public FragmentCommunicator fComm;
    public ImageButton res1, res2;
    int c;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_test, container, false);

    public void onAttach(Activity activity) {
        try {
            fComm = (FragmentCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement FragmentCommunicator");

    public void onActivityCreated(Bundle savedInstanceState) {
        res1 = (ImageButton) getActivity().findViewById(;
        res2 = (ImageButton) getActivity().findViewById(;
    public void onClick(final View v) { //check for what button is pressed
            switch (v.getId()) {
                  c *= fComm.fragmentContactActivity(2);
                  c *= fComm.fragmentContactActivity(4);
                  c *= fComm.fragmentContactActivity(100);
    public interface FragmentCommunicator{
        public int fragmentContactActivity(int b);

public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
    int a = 10;
    //variable a is update by fragment. ex. use to change textview or whatever else you'd like.

    public int fragmentContactActivity(int b) {
        //update info on activity here
        a += b;
        return a;

psql: FATAL: Ident authentication failed for user "postgres"

I've spent more time solving this error that I care to admit.

The order of authentication configuration in pg_hba.conf is relevant in your case I think. The default configuration file includes several lines in a vanilla install. These defaults can match the conditions of your authentication attempts resulting in a failure to authenticate. It fails regardless of additional configuration added at the end of the .conf file.

To check which line of configuration is use make sure to look at the default log file for messages. You might see something like this

LOG:  could not connect to Ident server at address "", port 113: Connection refused
FATAL:  Ident authentication failed for user "acme" 
DETAIL:  Connection matched pg_hba.conf line 82: "host     all             all               ident"

It turns out this default line is causing the rejection.

host    all             all               ident

try commenting it out.

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: or

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

how to check redis instance version?

To get the version of Redis server

redis-server -v

To get the version of Redis client

redis-cli -v

How to resolve cURL Error (7): couldn't connect to host?


is very explicit ... it means Failed to connect() to host or proxy.

The following code would work on any system:

$ch = curl_init("");    // initialize curl handle
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);

If you can not see google page then .. your URL is wrong or you have some firewall or restriction issue.

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')

Thank you...

How do I merge dictionaries together in Python?

You can use the .update() method if you don't need the original d2 any more:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.


>>> d1 = {'a': 1, 'b': 2} 
>>> d2 = {'b': 1, 'c': 3}
>>> d2.update(d1)
>>> d2
{'a': 1, 'c': 3, 'b': 2}


Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy should also be considered.

EditText, clear focus on touch outside

You've probably found the answer to this problem already but I've been looking on how to solve this and still can't really find exactly what I was looking for so I figured I'd post it here.

What I did was the following (this is very generalized, purpose is to give you an idea of how to proceed, copying and pasting all the code will not work O:D ):

First have the EditText and any other views you want in your program wrapped by a single view. In my case I used a LinearLayout to wrap everything.


Then in your code you have to set a Touch Listener to your main LinearLayout.

final EditText searchEditText = (EditText) findViewById(;
mainLinearLayout.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
                if(event.getY() >= 72){
                    //Will only enter this if the EditText already has focus
                    //And if a touch event happens outside of the EditText
                    //Which in my case is at the top of my layout
                    //and 72 pixels long
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
            return false;

I hope this helps some people. Or at least helps them start solving their problem.

How can I read user input from the console?

string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;

The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.

Cannot execute RUN mkdir in a Dockerfile

When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p flag to mkdir ... Please update your Dockerfile with

RUN mkdir -p ... 

I tested this and it's correct.

How do I get the directory that a program is running from?

Just to belatedly pile on here,...

there is no standard solution, because the languages are agnostic of underlying file systems, so as others have said, the concept of a directory based file system is outside the scope of the c / c++ languages.

on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is - ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.

How to load local file in sc.textFile, instead of HDFS

I tried the following and it worked from my local file system.. Basically spark can read from local, HDFS and AWS S3 path


UnicodeEncodeError: 'charmap' codec can't encode characters

In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)

Replacing this line:

with open('filename', 'w') as f:

With this:

with open('filename', 'w', encoding='utf-8') as f:

The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.

Retrieving the COM class factory for component failed

This did the trick for me: (solution from the msdn forum)

goto Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

right click to get properties dialog. Goto Security tab and customize permissions accordingly.

In Launch and Application Permissions, select Customize, Edit. Add the user / group that calls the application.

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*, axis=1)
>>> df
   b  c  index_x10
1  2  3         10
4  5  6         40

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

If you are on MAMP

Check your port number as well generally it is

Host localhost

Port 8889

User root

Password root

Socket /Applications/MAMP/tmp/mysql/mysql.sock

mysqli_real_connect(): (HY000/2002): No such file or directory

This worked for me.



$cfg['Servers'][$i]['host'] = 'localhost';


$cfg['Servers'][$i]['host'] = '';


Then rename the file and remove sample from the name.

Angular, content type is not being sent with $http

    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"

    $scope.response = response;
    $scope.error = error;

Try like this.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.


EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress":

How to find files that match a wildcard string in Java?

Simple Way without using any external import is to use this method

I created csv files named with billing_201208.csv ,billing_201209.csv ,billing_201210.csv and it looks like working fine.

Output will be the following if files listed above exists

found billing_201208.csv
found billing_201209.csv
found billing_201210.csv

    //Use Import ->import
        public static void main(String[] args) {
        String pathToScan = ".";
        String target_file ;  // fileThatYouWantToFilter
        File folderToScan = new File(pathToScan); 

    File[] listOfFiles = folderToScan.listFiles();

     for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                target_file = listOfFiles[i].getName();
                if (target_file.startsWith("billing")
                     && target_file.endsWith(".csv")) {
                //You can add these files to fileList by using "list.add" here
                     System.out.println("found" + " " + target_file); 

Various ways to remove local Git changes

1. When you don't want to keep your local changes at all.

git reset --hard

This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.

2. When you want to keep your local changes

If you want to pull the new changes from remote and want to ignore the local changes during this pull then,

git stash

It will stash all the local changes, now you can pull the remote changes,

git pull

Now, you can bring back your local changes by,

git stash pop

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
canvas.drawBitmap(wrench, left, top, null);

Numpy converting array from float to strings

This is probably slower than what you want, but you can do:

>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)

It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.

Is it acceptable and safe to run pip install under sudo?

Is it acceptable & safe to run pip install under sudo?

It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'? To install Python package in your home directory you don't need root privileges. See description of --user option to pip.

GitHub center image

I've been looking at the markdown syntax used in github [...], I can't figure out how to center an image


No you can't by only relying on Markdown syntax. Markdown doesn't care with positioning.

Note: Some markdown processors support inclusion of HTML (as rightfully pointed out by, and in the GitHub case you may fallback to something like <div style="text-align:center"><img src="..." /></div>. Beware that there's no guarantee the image will be centered if your repository is forked in a different hosting environment (Codeplex, BitBucket, ...) or if the document isn't read through a browser (Sublime Text Markdown preview, MarkdownPad, VisualStudio Web Essentials Markdown preview, ...).

Note 2: Keep in mind that even within the GitHub website, the way markdown is rendered is not uniform. The wiki, for instance, won't allow such css positional trickery.

Unabridged version

The Markdown syntax doesn't provide one with the ability to control the position of an image.

In fact, it would be borderline against the Markdown philosophy to allow such formatting, as stated in the "Philosophy" section

"A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. "

Markdown files are rendered by website through the use of the Ruby Redcarpet library.

Redcarpet exposes some extensions (such as strikethrough, for instance) which are not part of standard Markdown syntax and provide additional "features". However, no supported extension allow you to center an image.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution was to insert <packaging>pom</packaging> between artifactId and version


Simple Vim commands you wish you'd known earlier

:shell to launch a shell console from Vim. Useful when for example you want to test a script without quitting Vim. Simply hit ^d when you done with the shell console, and then you come back to Vim and your edited file.

Assigning the return value of new by reference is deprecated

Upgrade your pear/MDB2 from console:

# pear upgrade MDB2-beta
# pear upgrade MDB2_Driver_Mysql-beta

Problem solved at version 2.5.0b3

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here:

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
        }, 0);

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

Convert AM/PM time to 24 hours format?

Convert a string to a DateTime, you could try

    DateTime timeValue = Convert.ToDateTime("01:00 PM");

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>

Check if string contains only digits

if you want to include float values also you can use the following code

var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 =  /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);

this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .

example :

 theValue=3.4; //isnum1=true , isnum2=true 
theValue=.4; //isnum1=true , isnum2=false 
theValue=3.; //isnum1=flase , isnum2=true 

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

get UTC timestamp in python with datetime

Simplest way:

>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")

Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:

>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())

In fact, its not even necessary to specify timezone.utc, because the time difference is the same so long as both datetime have the same timezone (or no timezone).

>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())

What is a MIME type?

I couldn't possibly explain it better than wikipedia does:

In addition to e-mail applications, Web browsers also support various MIME types. This enables the browser to display or output files that are not in HTML format.

IOW, it helps the browser (or content consumer, because it may not just be a browser) determine what content they are about to consume; this means a browser may be able to make a decision on the correct plugin to use to display content, or a media player may be able to load up the correct codec or plugin.

How do I import a pre-existing Java project into Eclipse and get up and running?

  1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).

  2. Also create a lib folder (the name isn't that important, but it follows standard conventions).

  3. Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).

  4. Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)

  5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)

  6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.

  7. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.

  8. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.

That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

sql query distinct with Row_Number

Try this:

               SELECT DISTINCT id FROM table WHERE fid = 64
  FROM cte
 WHERE fid = 64

Comparing two NumPy arrays for equality, element-wise


test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

Didn't find class ""?

I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the below method

protected void attachBaseContext(Context base) {

and add MultiDex.install(this); in that method means

protected void attachBaseContext(Context base) {

Note :- Don't forget to follow above steps

How to convert float to varchar in SQL Server

I just came across a similar situation and was surprised at the rounding issues of 'very large numbers' presented within SSMS v17.9.1 / SQL 2017.

I am not suggesting I have a solution, however I have observed that FORMAT presents a number which appears correct. I can not imply this reduces further rounding issues or is useful within a complicated mathematical function.

T SQL Code supplied which should clearly demonstrate my observations while enabling others to test their code and ideas should the need arise.

WITH Units AS 
   SELECT 1.0 AS [RaisedPower] , 'Ten' As UnitDescription
   SELECT 2.0 AS [RaisedPower] , 'Hundred' As UnitDescription
   SELECT 3.0 AS [RaisedPower] , 'Thousand' As UnitDescription
   SELECT 6.0 AS [RaisedPower] , 'Million' As UnitDescription
   SELECT 9.0 AS [RaisedPower] , 'Billion' As UnitDescription
   SELECT 12.0 AS [RaisedPower] , 'Trillion' As UnitDescription
   SELECT 15.0 AS [RaisedPower] , 'Quadrillion' As UnitDescription
   SELECT 18.0 AS [RaisedPower] , 'Quintillion' As UnitDescription
   SELECT 21.0 AS [RaisedPower] , 'Sextillion' As UnitDescription
   SELECT 24.0 AS [RaisedPower] , 'Septillion' As UnitDescription
   SELECT 27.0 AS [RaisedPower] , 'Octillion' As UnitDescription
   SELECT 30.0 AS [RaisedPower] , 'Nonillion' As UnitDescription
   SELECT 33.0  AS [RaisedPower] , 'Decillion' As UnitDescription


SELECT UnitDescription

   ,              POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )                                                             AS ReturnsFloat
   ,        CAST( POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  AS NUMERIC (38,0) )                                        AS RoundingIssues
   , STR(   CAST( POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  AS NUMERIC (38,0) ) ,   CAST([RaisedPower] AS INT) + 2, 0) AS LessRoundingIssues
   , FORMAT(      POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  , '0')                                                     AS NicelyFormatted

FROM Units
ORDER BY [RaisedPower]

Blur the edges of an image or background image with CSS

<meta charset="utf-8">

#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */

#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */



<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>


Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

Execute jQuery function after another function completes

Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.

function Typer()
var dfd = $.Deferred();
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];



  var timer=    setInterval(function() {
                    if(i == srcText.length) {

    // clearInterval(this);



                        result += srcText[i].replace("\n", "<br />");
                        $("#message").html( result);
              return dfd.promise();

I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.

   function playBGM()
      var playsound = $.Deferred();
      $("#bgm").on("ended", function() {
        return playsound.promise();

    function thirdFunction() {
        alert('third function');

Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)


Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.

Dart: mapping a list (

you can use => Tab(text: title)).toList()


    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs: => Tab(text: title)).toList()

How to get the list of files in a directory in a shell script?

Just enter this simple command:

ls -d */

Best C++ IDE or Editor for Windows

Visual studio is the most up to date and probably "best" free ide. Dev C++ is a little dated, and mingw doesn't compile most of boost, (except regex). Most of the other compilers are dated and fading, like mars and borland. But you can use whatever you like!

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all

You need to change: AllowOverride None To: AllowOverride All

text-align: right; not working for <label>

As stated in other answers, label is an inline element. However, you can apply display: inline-block to the label and then center with text-align.

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;

Why display: inline-block and not display: inline? For the same reason that you can't align label, it's inline.

Why display: inline-block and not display: block? You could use display: block, but it will be on another line. display: inline-block combines the properties of inline and block. It's inline, but you can also give it a width, height, and align it.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Why is Android Studio reporting "URI is not registered"?

For me, i clone a project from gitlab, there is table of contents:


then i encounter this problem, i solve the problem by below method:

  • remove the middle path "TradeClient", as TradeClient/app/...
  • then File -> Invalidate Caches / Restart...

Javascript return number of days,hours,minutes,seconds between two dates

The best library that I know of for duration breakdown is countdown.js. It handles all the hard cases such as leap years and daylight savings as csg mentioned, and even allows you to specify fuzzy concepts such as months and weeks. Here's the code for your case:

//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374; 
var date_future = 29384744;

diff = countdown(date_now * 1000, date_future * 1000, 
            countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours + 
      " minutes: " + diff.minutes + " seconds: " + diff.seconds);

//or even better

Here's a JSFiddle, but it would probably only work in FireFox or in Chrome with web security disabled, since countdown.js is hosted with a text/plain MIME type (you're supposed to serve the file, not link to

Concatenating strings in C, which method is more efficient?

Neither is terribly efficient since both methods have to calculate the string length or scan it each time. Instead, since you calculate the strlen()s of the individual strings anyway, put them in variables and then just strncpy() twice.

Are HTTPS headers encrypted?

New answer to old question, sorry. I thought I'd add my $.02

The OP asked if the headers were encrypted.

They are: in transit.

They are NOT: when not in transit.

So, your browser's URL (and title, in some cases) can display the querystring (which usually contain the most sensitive details) and some details in the header; the browser knows some header information (content type, unicode, etc); and browser history, password management, favorites/bookmarks, and cached pages will all contain the querystring. Server logs on the remote end can also contain querystring as well as some content details.

Also, the URL isn't always secure: the domain, protocol, and port are visible - otherwise routers don't know where to send your requests.

Also, if you've got an HTTP proxy, the proxy server knows the address, usually they don't know the full querystring.

So if the data is moving, it's generally protected. If it's not in transit, it's not encrypted.

Not to nit pick, but data at the end is also decrypted, and can be parsed, read, saved, forwarded, or discarded at will. And, malware at either end can take snapshots of data entering (or exiting) the SSL protocol - such as (bad) Javascript inside a page inside HTTPS which can surreptitiously make http (or https) calls to logging websites (since access to local harddrive is often restricted and not useful).

Also, cookies are not encrypted under the HTTPS protocol, either. Developers wanting to store sensitive data in cookies (or anywhere else for that matter) need to use their own encryption mechanism.

As to cache, most modern browsers won't cache HTTPS pages, but that fact is not defined by the HTTPS protocol, it is entirely dependent on the developer of a browser to be sure not to cache pages received through HTTPS.

So if you're worried about packet sniffing, you're probably okay. But if you're worried about malware or someone poking through your history, bookmarks, cookies, or cache, you are not out of the water yet.

How do I add slashes to a string in Javascript?

An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.


That will replace all single quotes with the hex code for single quote.

How to format DateTime in Flutter , How to get current time in flutter?

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

What are some ways of accessing Microsoft SQL Server from Linux?

If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine.

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Node.js console.log() not logging anything

This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.

myApp.service('serverOperations', function($http) {
        this.get_data = function(user) {
          return $'http://localhost/serverOperations.php?action=get_data', user);

myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {        
        .then( function(response) {

Using Powershell to stop a service remotely without WMI or remoting

As far as I know, and I cant verify it now, you cannot stop remote services with the Stop-Service cmdlet or with .Net, it is not supported.

Yes it works, but it stopes the service on your local machine, not on the remote computer.

Now, if the above is correct, without remoting or wmi enabled, you could set a scheduled job on the remote system, using AT, that runs Stop-Service locally.

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

Setting equal heights for div's with jQuery

So, below the jquery script to set the equal height to column which Math.max will calculate the two divs height and takes the highest height either it may be left or right.

$(document).ready(function() {
var Equalheights = Math.max($(“#left”).height(), $(“#right”).height());
$(“#left”). Equalheights(d);
$(“#right”). Equalheights(d);
Highest height will be assigned to both left and right divs

Live Demo

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:


AngularJS - Multiple ng-view in single template

UI-Router is a project that can help: One of it's features is Multiple Named Views

UI-Router has many features and i recommend you using it if you're working on an advanced app.

Check documentation of Multiple Named Views here.

how to make pop up Modal?

Modal Window using ExtJS approach.

In Main Window

<link rel="stylesheet" href="ext.css" type="text/css">
<script type="text/javascript" src="ext-all.js"></script>

function openModalDialog() {
    Ext.onReady(function() {
        Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: Ext.getBody().getViewSize().height*0.8,
        width: Ext.getBody().getViewSize().width*0.8,
        layout: 'fit',
        itemId : 'popUpWin',        
        items: [{
            xtype: 'box',
            autoEl: {
                     tag: 'iframe',
                     src: '2.html',
function closeExtWin(isSubmit) {
     if (isSubmit) {
          document.forms[0].userAction.value = "refresh";
   <form action="abc.jsp">
   <a href="javascript:openModalDialog()"> Click to open dialog </a>

In popupWindow 2.html

<script type="text\javascript">
function doSubmit(action) {
     if (action == 'save') {
     } else {
    <a href="javascript:doSubmit('save');" title="Save">Save</a>
    <a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

Jquery - animate height toggle

You should be using a class to achieve what you want:


#topbar { width: 100%; height: 40px; background-color: #000; }
#topbar.hide { height: 10px; }


      if($(this).hasClass('hide')) {
      } else { 

How can I find the number of years between two dates?


    LocalDate.of( 2010 , 1 , 1 ) , ZoneId.of( "America/Montreal" ) ) 


The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );

Dump to console.

System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;

start: 2010-01-01 | stop: 2016-09-06 | years: 6

Table of all date-time types in Java, both modern and legacy

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

MySQL - Get row number on select

It's now builtin in MySQL 8.0 and MariaDB 10.2:

  itemID, COUNT(*) as ordercount,
FROM orders

Recursively list files in Java

Based on stacker answer. Here is a solution working in JSP without any external libraries so you can put it almost anywhere on your server:

<!DOCTYPE html>
<%@ page session="false" %>
<%@ page import="java.util.*" %>
<%@ page import="*" %>
<%@ page contentType="text/html; charset=UTF-8" %>

    public List<String> files = new ArrayList<String>();
        Fills files array with all sub-files.
    public void walk( File root ) {
        File[] list = root.listFiles();

        if (list == null) return;

        for ( File f : list ) {
            if ( f.isDirectory() ) {
                walk( f );
            else {
    File jsp = new File(request.getRealPath(request.getServletPath()));
    File dir = jsp.getParentFile();
    String prefixPath = dir.getAbsolutePath() + "/";

Then you just do something like:

        <% for (String file : files) { %>
            <% if (file.matches(".+\\.(apk|ipa|mobileprovision)")) { %>
                <li><%=file.replace(prefixPath, "")%></li>
            <% } %>
        <% } %>

The definitive guide to form-based website authentication

Definitive Article

Sending credentials

The only practical way to send credentials 100% securely is by using SSL. Using JavaScript to hash the password is not safe. Common pitfalls for client-side password hashing:

  • If the connection between the client and server is unencrypted, everything you do is vulnerable to man-in-the-middle attacks. An attacker could replace the incoming javascript to break the hashing or send all credentials to their server, they could listen to client responses and impersonate the users perfectly, etc. etc. SSL with trusted Certificate Authorities is designed to prevent MitM attacks.
  • The hashed password received by the server is less secure if you don't do additional, redundant work on the server.

There's another secure method called SRP, but it's patented (although it is freely licensed) and there are few good implementations available.

Storing passwords

Don't ever store passwords as plaintext in the database. Not even if you don't care about the security of your own site. Assume that some of your users will reuse the password of their online bank account. So, store the hashed password, and throw away the original. And make sure the password doesn't show up in access logs or application logs. OWASP recommends the use of Argon2 as your first choice for new applications. If this is not available, PBKDF2 or scrypt should be used instead. And finally if none of the above are available, use bcrypt.

Hashes by themselves are also insecure. For instance, identical passwords mean identical hashes--this makes hash lookup tables an effective way of cracking lots of passwords at once. Instead, store the salted hash. A salt is a string appended to the password prior to hashing - use a different (random) salt per user. The salt is a public value, so you can store them with the hash in the database. See here for more on this.

This means that you can't send the user their forgotten passwords (because you only have the hash). Don't reset the user's password unless you have authenticated the user (users must prove that they are able to read emails sent to the stored (and validated) email address.)

Security questions

Security questions are insecure - avoid using them. Why? Anything a security question does, a password does better. Read PART III: Using Secret Questions in @Jens Roland answer here in this wiki.

Session cookies

After the user logs in, the server sends the user a session cookie. The server can retrieve the username or id from the cookie, but nobody else can generate such a cookie (TODO explain mechanisms).

Cookies can be hijacked: they are only as secure as the rest of the client's machine and other communications. They can be read from disk, sniffed in network traffic, lifted by a cross-site scripting attack, phished from a poisoned DNS so the client sends their cookies to the wrong servers. Don't send persistent cookies. Cookies should expire at the end of the client session (browser close or leaving your domain).

If you want to autologin your users, you can set a persistent cookie, but it should be distinct from a full-session cookie. You can set an additional flag that the user has auto-logged in, and needs to log in for real for sensitive operations. This is popular with shopping sites that want to provide you with a seamless, personalized shopping experience but still protect your financial details. For example, when you return to visit Amazon, they show you a page that looks like you're logged in, but when you go to place an order (or change your shipping address, credit card etc.), they ask you to confirm your password.

Financial websites such as banks and credit cards, on the other hand, only have sensitive data and should not allow auto-login or a low-security mode.

List of external resources

Can I mask an input text in a bat file?

make a batch file that calls the one needed for invisible characters then make a shortcut for the batch file being called.

right click




background == black



hope thus helps you!!!!!!!!

Add an element to an array in Swift

To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a "cached copy" of what was last pulled from origin, which is why it's called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the "remote branches".

How to copy part of an array to another array in C#?

int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4


Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:


Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Another possible solution depending on your situation.

If you know that is the same as then you can create a symlink by:

ln -s /lib/ /lib/

Then ls -l /lib should now show the symlink and what it points to.

How to split a data frame?

I just posted a kind of a RFC that might help you: Split a vector into chunks in R

x = data.frame(num = 1:26, let = letters, LET = LETTERS)
## number of chunks
n <- 2
dfchunk <- split(x, factor(sort(rank(row.names(x))%%n)))
   num let LET
1    1   a   A
2    2   b   B
3    3   c   C
4    4   d   D
5    5   e   E
6    6   f   F
7    7   g   G
8    8   h   H
9    9   i   I
10  10   j   J
11  11   k   K
12  12   l   L
13  13   m   M

   num let LET
14  14   n   N
15  15   o   O
16  16   p   P
17  17   q   Q
18  18   r   R
19  19   s   S
20  20   t   T
21  21   u   U
22  22   v   V
23  23   w   W
24  24   x   X
25  25   y   Y
26  26   z   Z

Cheers, Sebastian

Incorrect integer value: '' for column 'id' at row 1

Try to edit your and comment the original sql_mode and add sql_mode = "".

vi /etc/mysql/my.cnf

sql_mode = ""

save and quit...

service mysql restart

Subtract one day from datetime

Try this

SELECT DATEDIFF(DAY,  DATEADD(day, -1, '2013-03-13 00:00:00.000'), GETDATE())



Is there a numpy builtin to reject outliers from a list

Building on Benjamin's, using pandas.Series, and replacing MAD with IQR:

def reject_outliers(sr, iq_range=0.5):
    pcnt = (1 - iq_range) / 2
    qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
    iqr = qhigh - qlow
    return sr[ (sr - median).abs() <= iqr]

For instance, if you set iq_range=0.6, the percentiles of the interquartile-range would become: 0.20 <--> 0.80, so more outliers will be included.

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute after the last command of has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that contains such a command. If that is the case, then you need to modify the script:

cmd &

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

Java: Static Class?

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

Do copyright dates need to be updated?

Technically, you should update a copyright year only if you made contributions to the work during that year. So if your website hasn't been updated in a given year, there is no ground to touch the file just to update the year.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Use :after pseudo selector. Look


ul li { float: left; }
ul li:after { content: "|"; padding: 0 .5em; }


jQuery solution:


    <ul id="animals">


div { width: 300px; }
ul li { float: left; border-right: 1px solid black; padding: 0 .5em; }
ul li:last-child { border: 0; }


var maxWidth = 300, // Your div max-width
    totalWidth = 0;
$('#animals li').each(function(){
    var currentWidth = $(this).outerWidth(),
        nextWidth = $(this).next().outerWidth();
    totalWidth += currentWidth;
    if ( (totalWidth + nextWidth) > maxWidth ) {
        $(this).css('border', 'none');
        totalWidth = 0;

Take a look here. I also added a few more animals.

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

It is just:

float f = (float)6;

ModelState.IsValid == false, why?

If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.

Run all SQL files in a directory

  1. In the SQL Management Studio open a new query and type all files as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
  2. Go to Query menu on SQL Management Studio and make sure SQLCMD Mode is enabled
  3. Click on SQLCMD Mode; files will be selected in grey as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
  4. Now execute

Batch script to delete files

You need to escape the % with another...

del "D:\TEST\TEST 100%%\Archive*.TXT"

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

Fastest method to escape HTML tags as HTML entities?

I'm not entirely sure about speed, but if you are looking for simplicity I would suggest using the lodash/underscore escape function.

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

How do you get the path to the Laravel Storage folder?

For Laravel 5.x, use $storage_path = storage_path().

From the Laravel 5.0 docs:


Get the fully qualified path to the storage directory.

Note also that, for Laravel 5.1 and above, per the Laravel 5.1 docs:

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$path = storage_path('app/file.txt');

Function to close the window in Tkinter

def quit(self):

Add parentheses after destroy to call the method.

When you use command=self.root.destroy you pass the method to Tkinter.Button without the parentheses because you want Tkinter.Button to store the method for future calling, not to call it immediately when the button is created.

But when you define the quit method, you need to call self.root.destroy() in the body of the method because by then the method has been called.

Is it possible to format an HTML tooltip (title attribute)?

I know this is an old post but I would like to add my answer for future reference. I use jQuery and css to style my tooltips: easiest-tooltip-and-image-preview-using-jquery (for a demo: On my static websites this just worked great. However, during migrating to Wordpress it stopped. My solution was to change tags like <br> and <span> into this: &lt;br&gt; and &lt;span&gt; This works for me.

Moment.js - tomorrow, today and yesterday

So this is what I ended up doing

var dateText = moment(someDate).from(new Date());
var startOfToday = moment().startOf('day');
var startOfDate = moment(someDate).startOf('day');
var daysDiff = startOfDate.diff(startOfToday, 'days');
var days = {
  '0': 'today',
  '-1': 'yesterday',
  '1': 'tomorrow'

if (Math.abs(daysDiff) <= 1) {
  dateText = days[daysDiff];

How do I use Join-Path to combine more than two strings into a file path?

Here are two more ways to write a pure PowerShell function to join an arbitrary number of components into a path.

This first function uses a single array to store all of the components and then a foreach loop to combine them:

function Join-Paths {
    $output = $Paths[0]
    foreach($path in $Paths[1..$Paths.Count]) {
        $output = Join-Path $output -ChildPath $path

Because the path components are elements in an array and all part of a single argument, they must be separated by commas. Usage is as follows:

PS C:\> Join-Paths 'C:', 'Program Files', 'Microsoft Office'
C:\Program Files\Microsoft Office

A more minimalist way to write this function is to use the built-in $args variable, and then collapse the foreach loop into a single line using Mike Fair's method.

function Join-Paths2 {
    $path = $args[0]
    $args[1..$args.Count] | %{ $path = Join-Path $path $_ }

Unlike the previous version of the function, each path component is a separate argument, so only a space is necessary to separate the arguments:

PS C:\> Join-Paths2 'C:' 'Program Files' 'Microsoft Office'
C:\Program Files\Microsoft Office

error: the details of the application error from being viewed remotely

Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".

How to get the full path of running process?

A solution for:

  • Both 32-bit AND 64-bit processes
  • System.Diagnostics only (no System.Management)

I used the solution from Russell Gantman and rewritten it as an extension method you can use like this:

var process = Process.GetProcessesByName("explorer").First();
string path = process.GetMainModuleFileName();
// C:\Windows\explorer.exe

With this implementation:

internal static class Extensions {
    private static extern bool QueryFullProcessImageName([In] IntPtr hProcess, [In] uint dwFlags, [Out] StringBuilder lpExeName, [In, Out] ref uint lpdwSize);

    public static string GetMainModuleFileName(this Process process, int buffer = 1024) {
        var fileNameBuilder = new StringBuilder(buffer);
        uint bufferLength = (uint)fileNameBuilder.Capacity + 1;
        return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, ref bufferLength) ?
            fileNameBuilder.ToString() :

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";


$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

What is the purpose of using -pedantic in GCC/G++ compiler?

Basically, it will make your code a lot easier to compile under other compilers which also implement the ANSI standard, and, if you are careful in which libraries/api calls you use, under other operating systems/platforms.

The first one, turns off SPECIFIC features of GCC. (-ansi) The second one, will complain about ANYTHING at all that does not adhere to the standard (not only specific features of GCC, but your constructs too.) (-pedantic).

Parsing JSON Array within JSON Object

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = != -1) {
      sb.append((char) cp);
    return sb.toString();

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("sources");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:


to get the objects inside of the array.

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\ in line no 124 you are trying to access a null object which results in null pointer exception.

Make the image go behind the text and keep it in center using CSS

There are two ways to handle this.

  • Background Image
  • Using z-index property of CSS

The background image is probably easier. You need a fixed width somewhere.

.background-image {
    width: 400px;
    background: url(background.png) 50% 50%;
<form><div class="background-image"></div></form>

In a URL, should spaces be encoded using %20 or +?

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20" or "+". From the section "Query strings" under "Recommendations":

Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:

3.4. Query Component The query component is a string of information to be interpreted by the resource.

   query         = *uric

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+" characters.

As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode() is to then call replaceAll("\\+","%20") on the return value.

The following untracked working tree files would be overwritten by merge, but I don't care

A replacement for git merge that will overwrite untracked files

The comments below use 'FOI' for the 'files of interest', the files that

  • exist in the donor branch,
  • do not exist in the receiving branch,
  • and are blocking the merge because they are present and untracked in your working directory.
git checkout -f donor-branch   # replace FOI with tracked `donor` versions
git checkout receiving-branch  # FOI are not in `receiving`, so they disapppear
git merge donor-branch  # now the merge works

A replacement for git pull that will overwrite untracked files

pull = fetch + merge, so we do git fetch followed by the git checkout -f, git checkout, git merge trick above.

git fetch origin  # fetch remote commits
git checkout -f origin/mybranch  # replace FOI with tracked upstream versions
git checkout mybranch  # FOI are not in mybranch, so they disapppear
git merge origin/mybranch  # Now the merge works. fetch + merge completes the pull.

Detailed explanation

git merge -f does not exist, but git checkout -f does.

We will use git checkout -f + git checkout to remove the Files Of Interest (see above), and then your merge can proceed normally.

Step 1. This step forcibly replaces untracked FOI with tracked versions of the donor branch (it also checks out the donor branch, and updates the rest of the working dir).

git checkout -f donor-branch

Step 2. This step removes the FOI because they they are tracked in our current (donor) branch, and absent in the receiving-branch we switch to.

git checkout receiving-branch

Step 3. Now that the FOI are absent, merging in the donor branch will not overwrite any untracked files, so we get no errors.

git merge donor-branch

How to remove specific elements in a numpy array

You can also use sets:

a = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
the_index_list = [2, 3, 6]

the_big_set = set(numpy.arange(len(a)))
the_small_set = set(the_index_list)
the_delta_row_list = list(the_big_set - the_small_set)

a = a[the_delta_row_list]

sqlplus statement from command line

I assume this is *nix?

Use "here document":

sqlplus -s user/pass <<+EOF
select 1 from dual;

EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):

$ echo 'select 1 from dual;'|sqlplus -s user/pw



How do I generate a random int number?

I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

public class A
    public A()
        var rnd=new Random();
    public int ID { get; private set; }
public class B
    public B()
        var rnd=new Random();
    public int ID { get; private set; }

Do you think you will get two different IDs? NOPE

class Program
    static void Main(string[] args)
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101

The solution is to always use a single static random generator. Like this:

public static class Utils
    public static readonly Random random=new Random();

public class A
    public A()
    public int ID { get; private set; }
public class B
    public B()
    public int ID { get; private set; }

Pinging servers in Python

After looking around, I ended up writing my own ping module, which is designed to monitor large numbers of addresses, is asynchronous and doesn't use a lot of system resources. You can find it here: It's Apache licensed, so you can use it in your project in any way you see fit.

The main reasons for implementing my own are the restrictions of the other approaches:

  • Many of the solutions mentioned here require an exec out to a command line utility. This is quite inefficient and resource hungry if you need to monitor large numbers of IP addresses.
  • Others mention some older python ping modules. I looked at those and in the end, they all had some issue or the other (such as not correctly setting packet IDs) and didn't handle the ping-ing of large numbers of addresses.

How do I implement charts in Bootstrap?

You can use a 3rd party library like Shield UI for charting - that is tested and works well on all legacy and new web browsers and devices.

Can I embed a .png image into an html page?

Quick google search says you can embed it like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
width="16" height="14" alt="embedded folder icon">

But you need a different implementation in Internet Explorer.

How to get disk capacity and free space of remote computer

PowerShell Fun

Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}

Generating Random Number In Each Row In Oracle Query

you don’t need a select … from dual, just write:

SELECT t.*, dbms_random.value(1,9) RandomNumber
  FROM myTable t

How can I make a list of lists in R?

If you are trying to keep a list of lists (similar to python's list.append()) then this might work:

a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))

> c
[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

How to use sed/grep to extract text between two words?

All the above solutions have deficiencies where the last search string is repeated elsewhere in the string. I found it best to write a bash function.

    function str_str {
      local str
      echo -n "$str"

    # test it ...
    mystr="this is a string"
    str_str "$mystr" "this " " string"

How to concatenate columns in a Postgres SELECT?

For example if there is employee table which consists of columns as:


if we want to concatenate f_name + l_name as name.

SELECT employee_number,f_name ::TEXT ||','|| l_name::TEXT  AS "NAME",email_id,phone_number,designation FROM EMPLOYEE;

Something like 'contains any' for Java set?

Wouldn't Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.

Comparing two byte arrays in .NET

I posted a similar question about checking if byte[] is full of zeroes. (SIMD code was beaten so I removed it from this answer.) Here is fastest code from my comparisons:

static unsafe bool EqualBytesLongUnrolled (byte[] data1, byte[] data2)
    if (data1 == data2)
        return true;
    if (data1.Length != data2.Length)
        return false;

    fixed (byte* bytes1 = data1, bytes2 = data2) {
        int len = data1.Length;
        int rem = len % (sizeof(long) * 16);
        long* b1 = (long*)bytes1;
        long* b2 = (long*)bytes2;
        long* e1 = (long*)(bytes1 + len - rem);

        while (b1 < e1) {
            if (*(b1) != *(b2) || *(b1 + 1) != *(b2 + 1) || 
                *(b1 + 2) != *(b2 + 2) || *(b1 + 3) != *(b2 + 3) ||
                *(b1 + 4) != *(b2 + 4) || *(b1 + 5) != *(b2 + 5) || 
                *(b1 + 6) != *(b2 + 6) || *(b1 + 7) != *(b2 + 7) ||
                *(b1 + 8) != *(b2 + 8) || *(b1 + 9) != *(b2 + 9) || 
                *(b1 + 10) != *(b2 + 10) || *(b1 + 11) != *(b2 + 11) ||
                *(b1 + 12) != *(b2 + 12) || *(b1 + 13) != *(b2 + 13) || 
                *(b1 + 14) != *(b2 + 14) || *(b1 + 15) != *(b2 + 15))
                return false;
            b1 += 16;
            b2 += 16;

        for (int i = 0; i < rem; i++)
            if (data1 [len - 1 - i] != data2 [len - 1 - i])
                return false;

        return true;

Measured on two 256MB byte arrays:

UnsafeCompare                           : 86,8784 ms
EqualBytesSimd                          : 71,5125 ms
EqualBytesSimdUnrolled                  : 73,1917 ms
EqualBytesLongUnrolled                  : 39,8623 ms

How to disable Excel's automatic cell reference change after copy/paste?

Try this: Left-click the tab, making a copy of the whole sheet, then cut the cells you want to keep the same and paste them into your original worksheet.

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

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

How can I use UIColorFromRGB in Swift?

UIColorFromRGB in Swift 4

button.layer.backgroundColor = UIColor(red: 112.0/255, green: 86.0/255, blue: 164.0/255, alpha: 1.0).cgColor

Tips for debugging .htaccess rewrite rules

Online .htaccess rewrite testing

I found this Googling for RegEx help, it saved me a lot of time from having to upload new .htaccess files every time I make a small modification.

from the site:

htaccess tester

To test your htaccess rewrite rules, simply fill in the url that you're applying the rules to, place the contents of your htaccess on the larger input area and press "Check Now" button.

How to calculate date difference in JavaScript?

This is how you can implement difference between dates without a framework.

function getDateDiff(dateOne, dateTwo) {
        if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
            dateOne = new Date(formatDate(dateOne));
            dateTwo = new Date(formatDate(dateTwo));
            dateOne = new Date(dateOne);
            dateTwo = new Date(dateTwo);            
        let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        let diffMonths = Math.ceil(diffDays/31);
        let diffYears = Math.ceil(diffMonths/12);

        let message = "Difference in Days: " + diffDays + " " +
                      "Difference in Months: " + diffMonths+ " " + 
                      "Difference in Years: " + diffYears;
        return message;

    function formatDate(date) {
         return date.split('-').reverse().join('-');

    console.log(getDateDiff("23-04-2017", "23-04-2018"));

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

How do function pointers in C work?

Function pointer is usually defined by typedef, and used as param & return value.

Above answers already explained a lot, I just give a full example:

#include <stdio.h>

#define NUM_A 1
#define NUM_B 2

// define a function pointer type
typedef int (*two_num_operation)(int, int);

// an actual standalone function
static int sum(int a, int b) {
    return a + b;

// use function pointer as param,
static int sum_via_pointer(int a, int b, two_num_operation funp) {
    return (*funp)(a, b);

// use function pointer as return value,
static two_num_operation get_sum_fun() {
    return &sum;

// test - use function pointer as variable,
void test_pointer_as_variable() {
    // create a pointer to function,
    two_num_operation sum_p = &sum;
    // call function via pointer
    printf("pointer as variable:\t %d + %d = %d\n", NUM_A, NUM_B, (*sum_p)(NUM_A, NUM_B));

// test - use function pointer as param,
void test_pointer_as_param() {
    printf("pointer as param:\t %d + %d = %d\n", NUM_A, NUM_B, sum_via_pointer(NUM_A, NUM_B, &sum));

// test - use function pointer as return value,
void test_pointer_as_return_value() {
    printf("pointer as return value:\t %d + %d = %d\n", NUM_A, NUM_B, (*get_sum_fun())(NUM_A, NUM_B));

int main() {

    return 0;

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:


This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

Reference requirements.txt for the install_requires kwarg in setuptools file

It can't take a file handle. The install_requires argument can only be a string or a list of strings.

You can, of course, read your file in the setup script and pass it as a list of strings to install_requires.

import os
from setuptools import setup

with open('requirements.txt') as f:
    required =


Activate a virtualenv with a Python script

Just a simple solution that works for me. I don't know why you need the Bash script which basically does a useless step (am I wrong ?)

import os
os.system('/bin/bash  --rcfile flask/bin/activate')

Which basically does what you need:

[hellsing@silence Foundation]$ python2.7
(flask)[hellsing@silence Foundation]$

Then instead of deactivating the virtual environment, just Ctrl + D or exit. Is that a possible solution or isn't that what you wanted?


If its a SOAP 1.1 service then you will also need to include a SOAPAction HTTP header field:

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

The menu location seems to have changed to:

Query Designer --> Pane --> SQL

AppendChild() is not a function javascript

Just change

var div = '<div>top div</div>'; // you just created a text string


var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";

Tensorflow: how to save/restore a model?

All the answers here are great, but I want to add two things.

First, to elaborate on @user7505159's answer, the "./" can be important to add to the beginning of the file name that you are restoring.

For example, you can save a graph with no "./" in the file name like so:

# Some graph defined up here with specific names

saver = tf.train.Saver()
save_file = 'model.ckpt'

with tf.Session() as sess:, save_file)

But in order to restore the graph, you may need to prepend a "./" to the file_name:

# Same graph defined up here

saver = tf.train.Saver()
save_file = './' + 'model.ckpt' # String addition used for emphasis

with tf.Session() as sess:
    saver.restore(sess, save_file)

You will not always need the "./", but it can cause problems depending on your environment and version of TensorFlow.

It also want to mention that the can be important before restoring the session.

If you are receiving an error regarding uninitialized variables when trying to restore a saved session, make sure you include before the saver.restore(sess, save_file) line. It can save you a headache.

find path of current folder - cmd

2015-03-30: Edited - Missing information has been added

To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory

set "curpath=%cd%"

This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with

for %%a in ("%cd%\") do set "curpath=%%~fa"

Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash.

Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory

for %%a in (".\") do set "curpath=%%~fa"

Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command).

BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.

set "curpath=%~dp0"

It will return the directory where the batch file is stored, with an ending backslash.

BUT this will fail if in the batch file the shift command has been used

echo %~dp0

As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost.

To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine

@echo off
    setlocal enableextensions

    rem Destroy batch file reference
    echo batch folder is "%~dp0"

    rem Call the subroutine to get the batch folder 
    call :getBatchFolder batchFolder
    echo batch folder is "%batchFolder%"

    exit /b

:getBatchFolder returnVar
    set "%~1=%~dp0" & exit /b

This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).

How can I format a list to print each element on a separate line in python?

Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:

from __future__ import print_function  # Py 2.6+; In Py 3k not needed

mylist = ['10', 12, '14']    # Note that 12 is an int




Eventually, print as Python statement will go away... Might as well start to get used to it.

svn: E155004: ..(path of resource).. is already locked

Still if it doesn't work, just lock all the files and unlock. Now clean up again, It will work.

svn update svn cleanup

Use cases for the 'setdefault' dict method

One drawback of defaultdict over dict (dict.setdefault) is that a defaultdict object creates a new item EVERYTIME non existing key is given (eg with ==, print). Also the defaultdict class is generally way less common then the dict class, its more difficult to serialize it IME.

P.S. IMO functions|methods not meant to mutate an object, should not mutate an object.

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

Detect URLs in text with JavaScript

Based on Crescent Fresh answer

if you want to detect links with http:// OR without http:// and by www. you can use the following

function urlify(text) {
    var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
    //var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url,b,c) {
        var url2 = (c == 'www.') ?  'http://' +url : url;
        return '<a href="' +url2+ '" target="_blank">' + url + '</a>';

CSS /JS to prevent dragging of ghost image?

In React all you need is:

    onMouseDown={(e) => {
      // other code

Is <img> element block level or inline level?

For almost all purposes think of them as an inline element with a width set. Basically you are free to dictate how you would like images to display using CSS. I generally set a few image classes like so: {display:block;margin:0 auto;}

img.left {float:left;margin-right:10px;}

img.right  {float:right;margin-left:10px;}

img.border  {border:1px solid #333;}

Java Regex Replace with Capturing Group

Java 9 offers a Matcher.replaceAll() that accepts a replacement function:

resultString = regexMatcher.replaceAll(
        m -> String.valueOf(Integer.parseInt( * 3));

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Your selector is a little off, it's missing the trailing ]

var mySelect = $('select[name=' + name + ']')

you may also need to put quotes around the name, like so:

var mySelect = $('select[name="' + name + '"]')

How to set a Postgresql default value datestamp like 'YYYYMM'?

Right. Better to use a function:

    LANGUAGE 'plpgsql' AS $$
    retval text;
    m integer;
    retval := EXTRACT(year from current_timestamp);
    m := EXTRACT(month from current_timestamp);
    IF m < 10 THEN retval := retval || '0'; END IF;
    RETURN retval || m;
END $$;

SELECT yyyymm();

    key             int PRIMARY KEY,
    colname text DEFAULT yyyymm()
INSERT INTO foo (key) VALUES (0);

This gives me

 key | colname 
   0 | 200905

Make sure you run createlang plpgsql from the Unix command line, if necessary.

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
p { background-color: #ddd;}
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_

Convert.ToDateTime: how to set format

If value is a string in that format and you'd like to convert it into a DateTime object, you can use DateTime.ParseExact static method:

DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);


string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);




Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class


*----------------Sorry I oversight, for static function already answered the question by adrift*



I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

addID in jQuery?

Like this :

var id = $('').attr('id');
$('').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

How can you represent inheritance in a database?

In addition at the Daniel Vassallo solution, if you use SQL Server 2016+, there is another solution that I used in some cases without considerable lost of performances.

You can create just a table with only the common field and add a single column with the JSON string that contains all the subtype specific fields.

I have tested this design for manage inheritance and I am very happy for the flexibility that I can use in the relative application.

How to force remounting on React components?

Use setState in your view to change employed property of state. This is example of React render engine.

 someFunctionWhichChangeParamEmployed(isEmployed) {
          employed: isEmployed

 getInitialState() {
      return {
          employed: true

    if (this.state.employed) {
        return (
                <MyInput ref="job-title" name="job-title" />
    } else {
        return (
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />

AVD Manager - Cannot Create Android Virtual Device

Had the exact same trouble... loading the ARM EABI v7a System Image worked for me too. Thanks very much.

I had previously seen on the Android SDK manager that a system image with the same name (ARM EABI v7a System Image) WAS installed on my system for a more recent SDK (Android 4.2). Consequently I thought it would negate the need to install the earlier Android 2.2 SDK ARM image, but apparently not.

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

You are missing a 'b' I think?

sudo service mongod start

should be

sudo service mongodb start

I think this is the case?

Angular 2 - innerHTML styling

If you're trying to style dynamically added HTML elements inside an Angular component, this might be helpful:

// inside component class...
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
  const attrs = this.hostRef.nativeElement.attributes
  for (let i = 0, l = attrs.length; i < l; i++) {
    if (attrs[i].name.startsWith('_nghost-c')) {
      return `_ngcontent-c${attrs[i].name.substring(9)}`
ngAfterViewInit() {
  // dynamically add HTML element
  dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')

My guess is that the convention for this attribute is not guaranteed to be stable between versions of Angular, so that one might run into problems with this solution when upgrading to a new version of Angular (although, updating this solution would likely be trivial in that case).

How to paste into a terminal?

same for Terminator

Ctrl + Shift + V

Look at your terminal key-bindings if any if that doesn't work

DynamoDB vs MongoDB NoSQL

We chose a combination of Mongo/Dynamo for a healthcare product. Basically mongo allows better searching, but the hosted Dynamo is great because its HIPAA compliant without any extra work. So we host the mongo portion with no personal data on a standard setup and allow amazon to deal with the HIPAA portion in terms of infrastructure. We can query certain items from mongo which bring up documents with pointers (ID's) of the relatable Dynamo document.

The main reason we chose to do this using mongo instead of hosting the entire application on dynamo was for 2 reasons. First, we needed to preform location based searches which mongo is great at and at the time, Dynamo was not, but they do have an option now.

Secondly was that some documents were unstructured and we did not know ahead of time what the data would be, so for example lets say user a inputs a document in the "form" collection like this: {"username": "user1", "email": "[email protected]"}. And another user puts this in the same collection {"phone": "813-555-3333", "location": [28.1234,-83.2342]}. With mongo we can search any of these dynamic and unknown fields at any time, with Dynamo, you could do this but would have to make a index every time a new field was added that you wanted searchable. So if you have never had a phone field in your Dynamo document before and then all of the sudden, some one adds it, its completely unsearchable.

Now this brings up another point in which you have mentioned. Sometimes choosing the right solution for the job does not always mean choosing the best product for the job. For example you may have a client who needs and will use the system you created for 10+ years. Going with a SaaS/IaaS solution that is good enough to get the job done may be a better option as you can rely on amazon to have up-kept and maintained their systems over the long haul.

How to split a string with any whitespace chars as delimiters

Since it is a regular expression, and i'm assuming u would also not want non-alphanumeric chars like commas, dots, etc that could be surrounded by blanks (e.g. "one , two" should give [one][two]), it should be:


How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

     getUnits: function() {...}

Working fiddle:

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link

Transport endpoint is not connected

So interestingly enough this error "Transport endpoint is not connected" was caused by my having more than one Veracrypt device mounted. I closed the extra device and suddenly I had access to the drive. Hmm..

How do you convert epoch time in C#?

Since .Net 4.6 and above please use DateTimeOffset.Now.ToUnixTimeSeconds()

If table exists drop table then create it, if it does not exist just create it

I needed to drop a table and re-create with a data from a view. I was creating a table out of a view and this is what I did:

DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;

The above worked for me using MySQL MariaDb.

Hibernate JPA Sequence (non-Id)

I know this is a very old question, but it's showed firstly upon the results and jpa has changed a lot since the question.

The right way to do it now is with the @Generated annotation. You can define the sequence, set the default in the column to that sequence and then map the column as:

@Column(name = "column_name", insertable = false)

How to get margin value of a div in plain JavaScript?

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).


var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

Live Copy | Source

How to import set of icons into Android Studio project

just like Gregory Seront said here:

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

but if your not getting the images from a generator site (maybe your UX team provides them), just make sure your folders are named drawable-hdpi, drawable-mdpi, etc. then in mac select all folders by holding shift and then copy them (DO NOT DRAG). Paste the folders into the res folder. android will take care of the rest and copy all drawables into the correct folder.