Programs & Examples On #Undo redo

For issues relating to undo and/or redo operations.

How do you 'redo' changes after 'undo' with Emacs?

To undo: C-_

To redo after a undo: C-g C-_

Type multiple times on C-_ to redo what have been undone by C-_ To redo an emacs command multiple times, execute your command then type C-xz and then type many times on z key to repeat the command (interesting when you want to execute multiple times a macro)

How to go back (ctrl+z) in vi/vim

The answer, u, (and many others) is in $ vimtutor.

How can I disable selected attribute from select2() dropdown Jquery?

The below code also works fine for Select2 3.x

For Enable Select Box:

$('#foo').select2('enable');

For Disable Select Box:

$('#foo').select2('disable');

jsfiddle: http://jsfiddle.net/DcunN/

Difference between Eclipse Europa, Helios, Galileo

In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").

Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.

Resource from src/main/resources not found after building with maven

FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
                     .getResourceAsStream("config.txt");

Or you could extract the file from the jar before reading it.

Implement a simple factory pattern with Spring 3 annotations

Following the answer from DruidKuma and jumping_monkey

You can also include optional and make your code a bit nicer and cleaner:

 public static MyService getService(String type) {
        return Optional.ofNullable(myServiceCache.get(type))
                .orElseThrow(() -> new RuntimeException("Unknown service type: " + type));
 }

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

I think the best way is to typing well your variables. You can do this by using the "typing" library.

Example:

from typing import NewType UserId = NewType ('UserId', int) some_id = UserId (524313)`

See https://docs.python.org/3/library/typing.html

How to create a <style> tag with Javascript?

All good, but for styleNode.cssText to work in IE6 with node created by javascipt, you need to append the node to the document before you set the cssText;

further info @ http://msdn.microsoft.com/en-us/library/ms533698%28VS.85%29.aspx

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

Declaring a python function with an array parameters and passing an array argument to the function call?

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

How can I grep for a string that begins with a dash/hyphen?

The correct way would be to use "--" to stop processing arguments, as already mentioned. This is due to the usage of getopt_long (GNU C-function from getopt.h) in the source of the tool.

This is why you notice the same phenomena on other command-line tools; since most of them are GNU tools, and use this call,they exhibit the same behavior.

As a side note - getopt_long is what gives us the cool choice between -rlo and --really_long_option and the combination of arguments in the interpreter.

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

Is it possible to auto-format your code in Dreamweaver?

ctrl+a->(click)commands->cleanup word HTML

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

Your using statements appear to be correct.

Are you, perhaps, missing the assembly reference to System.configuration.dll?

Right click the "References" folder in your project and click on "Add Reference..."

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

How to Initialize char array from a string

Perhaps your character array needs to be constant. Since you're initializing your array with characters from a constant string, your array needs to be constant. Try this:

#define S "ABCD"
const char a[] = { S[0], S[1], S[2], S[3] };

CardView Corner Radius

dependencies: compile 'com.android.support:cardview-v7:23.1.1'

<android.support.v7.widget.CardView
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:elevation="12dp"
    android:id="@+id/view2"
    app:cardCornerRadius="40dp"
    android:layout_centerHorizontal="true"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="1.9">
    <ImageView
        android:layout_height="80dp"
        android:layout_width="match_parent"
        android:id="@+id/imageView1"
        android:src="@drawable/Your_image"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
    </ImageView>
</android.support.v7.widget.CardView>

C Programming: How to read the whole file contents into a buffer

A portable solution could use getc.

#include <stdio.h>

char buffer[MAX_FILE_SIZE];
size_t i;

for (i = 0; i < MAX_FILE_SIZE; ++i)
{
    int c = getc(fp);

    if (c == EOF)
    {
        buffer[i] = 0x00;
        break;
    }

    buffer[i] = c;
}

If you don't want to have a MAX_FILE_SIZE macro or if it is a big number (such that buffer would be to big to fit on the stack), use dynamic allocation.

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

How to rename HTML "browse" button of an input type=file?

You can do it with a simple css/jq workaround: Create a fake button which triggers the browse button that is hidden.

HTML

<input type="file"/>
<button>Open</button>

CSS

input { display: none }

jQuery

$( 'button' ).click( function(e) {
    e.preventDefault(); // prevents submitting
    $( 'input' ).trigger( 'click' );
} );

demo

Pass props in Link react-router

there is a way you can pass more than one parameter. You can pass "to" as object instead of string.

// your route setup
<Route path="/category/:catId" component={Category} / >

// your link creation
const newTo = { 
  pathname: "/category/595212758daa6810cbba4104", 
  param1: "Par1" 
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>

// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104 
this.props.location.param1 // this is Par1

Run JavaScript code on window close or page refresh?

The event is called beforeunload, so you can assign a function to window.onbeforeunload.

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...

some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)

Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Forking / Multi-Threaded Processes | Bash

With GNU Parallel you can do:

cat file | parallel 'foo {}; foo2 {}; foo3 {}'

This will run one job on each cpu core. To run 50 do:

cat file | parallel -j 50 'foo {}; foo2 {}; foo3 {}'

Watch the intro videos to learn more:

http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

NSAttributedString add text alignment

Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [.font: titleFont,    
    .foregroundColor: UIColor.red, 
    .paragraphStyle: titleParagraphStyle])

Swift 3.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [NSFontAttributeName:titleFont,    
    NSForegroundColorAttributeName:UIColor.red, 
    NSParagraphStyleAttributeName: titleParagraphStyle])

(original answer below)

Swift 2.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center

let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
    attributes:[NSFontAttributeName:titleFont,   
    NSForegroundColorAttributeName:UIColor.redColor(), 
    NSParagraphStyleAttributeName: titleParagraphStyle])

MySQL error: key specification without a key length

Go to mysql edit table-> change column type to varchar(45).

UnicodeEncodeError: 'latin-1' codec can't encode character

I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:

Using UTF8 with Python MySQLdb

Edit: Quote from the above URL to satisfy the request in the first comment...

"UnicodeEncodeError:'latin-1' codec can't encode character ..."

This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect(), and "dbc" is the result of db.cursor().

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I used this recently (thanks to Alnitak):

#!/bin/bash
# activate child monitoring
set -o monitor

# locking subprocess
(while true; do sleep 0.001; done) &
pid=$!

# count, and kill when all done
c=0
function kill_on_count() {
    # you could kill on whatever criterion you wish for
    # I just counted to simulate bash's wait with no args
    [ $c -eq 9 ] && kill $pid
    c=$((c+1))
    echo -n '.' # async feedback (but you don't know which one)
}
trap "kill_on_count" CHLD

function save_status() {
    local i=$1;
    local rc=$2;
    # do whatever, and here you know which one stopped
    # but remember, you're called from a subshell
    # so vars have their values at fork time
}

# care must be taken not to spawn more than one child per loop
# e.g don't use `seq 0 9` here!
for i in {0..9}; do
    (doCalculations $i; save_status $i $?) &
done

# wait for locking subprocess to be killed
wait $pid
echo

From there one can easily extrapolate, and have a trigger (touch a file, send a signal) and change the counting criteria (count files touched, or whatever) to respond to that trigger. Or if you just want 'any' non zero rc, just kill the lock from save_status.

CSS Font Border?

I once tried to do those round corners and drop shadows with css3. Later on, I found it is still poorly supported (Internet Explorer(s), of course!)

I ended up trying to do that in JS (HTML canvas with IE Canvas), but it impacts the performance a lot (even on my C2D machine). In short, if you really need the effect, consider JS libraries (most of them should be able to run on IE6) but don't over do it due to performance issues; if you still need an alternative... you could use SFiR, then PS it and SFiR it. CSS3 isn't ready today.

Generate random password string with requirements in javascript

For someone who is looking for a simplest script. No while (true), no if/else, no declaration.

Base on mwag's answer, but this one uses crypto.getRandomValues, a stronger random than Math.random.

Array(20)
  .fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$')
  .map(x => x[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)])
  .join('');

See this for 0xffffffff.

Alternative 1

var generatePassword = (
  length = 20,
  wishlist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"
) => Array(length)
      .fill('')
      .map(() => wishlist[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * wishlist.length)])
      .join('');

console.log(generatePassword());

Alternative 2

var generatePassword = (
  length = 20,
  wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
  Array.from(crypto.getRandomValues(new Uint32Array(length)))
    .map((x) => wishlist[x % wishlist.length])
    .join('')

console.log(generatePassword())

Node.js

const crypto = require('crypto')

const generatePassword = (
  length = 20,
  wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
  Array.from(crypto.randomFillSync(new Uint32Array(length)))
    .map((x) => wishlist[x % wishlist.length])
    .join('')

console.log(generatePassword())

Android camera intent

private static final int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

How to run bootRun with spring profile via gradle task

Configuration for 4 different task with different profiles and gradle tasks dependencies:

  • bootRunLocal and bootRunDev - run with specific profile
  • bootPostgresRunLocal and bootPostgresRunDev same as prev, but executing custom task runPostgresDocker and killPostgresDocker before/after bootRun

build.gradle:

final LOCAL='local'
final DEV='dev'

void configBootTask(Task bootTask, String profile) {
    bootTask.main = bootJar.mainClassName
    bootTask.classpath = sourceSets.main.runtimeClasspath

    bootTask.args = [ "--spring.profiles.active=$profile" ]
//    systemProperty 'spring.profiles.active', profile // this approach also may be used
    bootTask.environment = postgresLocalEnvironment
}

bootRun {
    description "Run Spring boot application with \"$LOCAL\" profile"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunLocal(type: BootRun, dependsOn: 'classes') {
    description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunDev(type: BootRun, dependsOn: 'classes') {
    description "Run Spring boot application with \"$DEV\" profile"
    doFirst() {
        configBootTask(it, DEV)
    }
}

task bootPostgresRunLocal(type: BootRun) {
    description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootPostgresRunDev(type: BootRun) {
    description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, DEV)
    }
}

Copy a table from one database to another in Postgres

Same as answers by user5542464 and Piyush S. Wanare but split in two steps:

pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase > dump
cat dump | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase

otherwise the pipe asks the two passwords in the same time.

Best lightweight web server (only static content) for Windows

The smallest one I know is lighttpd.

Security, speed, compliance, and flexibility -- all of these describe lighttpd (pron. lighty) which is rapidly redefining efficiency of a webserver; as it is designed and optimized for high performance environments. With a small memory footprint compared to other web-servers, effective management of the cpu-load, and advanced feature set (FastCGI, SCGI, Auth, Output-Compression, URL-Rewriting and many more) lighttpd is the perfect solution for every server that is suffering load problems. And best of all it's Open Source licensed under the revised BSD license.

Edit: removed Windows version link, now a spam/malware plugin site.

Official way to ask jQuery wait for all images to load before executing something

None of the answers so far have given what seems to be the simplest solution.

$('#image_id').load(
  function () {
    //code here
});

Does bootstrap have builtin padding and margin classes?

There are built in classes, namely:

.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }

.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }

.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }

.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }

.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }

.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }

.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }

.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }

.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }

.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }

.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }

.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }

.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }

.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }

Java integer to byte array

The class org.apache.hadoop.hbase.util.Bytes has a bunch of handy byte[] conversion methods, but you might not want to add the whole HBase jar to your project just for this purpose. It's surprising that not only are such method missing AFAIK from the JDK, but also from obvious libs like commons io.

Why is access to the path denied?

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

I hit the same thing. Check to ensure that the file is NOT HIDDEN.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

EasyPHP is very good :

  • lightweight & portable : no windows service (like wamp)
  • easy to configure (all configuration files in the same folder : httpd.conf, php.ini & my.ini)
  • auto restarts apache when you edit httpd.conf

WAMP or UWAMP are good choices if you need to test with multiples versions of PHP and Apache.

But you can also use multiple versions of PHP with EasyPHP (by downloading the PHP version you need on php.net, and loading this version by editing httpd.conf) :

LoadModule php4_module "${path}/php4/php4apache2_2.dll"

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

C# equivalent of the IsNull() function in SQL Server

Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:

newValue = (oldValue is DBNull) ? null : oldValue;

How can I get a list of all open named pipes in Windows?

In the Windows Powershell console, type

[System.IO.Directory]::GetFiles("\\.\\pipe\\")

If your OS version is greater than Windows 7, you can also type
get-childitem \\.\pipe\

This returns a list of objects. If you want the name only:

(get-childitem \\.\pipe\).FullName

(The second example \\.\pipe\ does not work in Powershell 7, but the first example does)

What does question mark and dot operator ?. mean in C# 6.0?

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

It can be simplified to:

myAction?.Invoke(TValue);

DotNetFiddle Example:

using System;

public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

Result:

Test 2

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

Disabling of EditText in Android

As some answer mention it, if you disable the editText he become gray and if you set focusable false the cursor is displaying.

If you would like to do it only with xml this did the trick

       <YourFloatLabel
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

            <EditText
                android:id="@+id/view_ads_search_select"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:focusable="true"
                android:clickable="true"/>  
       </YourFloatLabel>

I simply add a FrameLayout appear above the editText and set it focusable and clickable so the editText can't be click.

Python convert decimal to hex

I recently made this python program to convert Decimal to Hexadecimal, please check this out. This is my first Answer in stack overflow .

decimal = int(input("Enter the Decimal no that you want to convert to Hexadecimal : "))
intact = decimal
hexadecimal = ''
dictionary = {1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}

while(decimal!=0):
    c = decimal%16 
    hexadecimal =  dictionary[c] + hexadecimal 
    decimal = int(decimal/16)

print(f"{intact} is {hexadecimal} in Hexadecimal")

When you Execute this code this will give output as:

Enter the Decimal no that you want to convert to Hexadecimal : 2766

2766 is ACE in Hexadecimal

Wordpress keeps redirecting to install-php after migration

Don't forget also the table prefixes if you installation don't use the default prefix.

How can I update NodeJS and NPM to the next versions?

Check your package version: npm -v [package-name]

Update it: npm update [-g] [package-name]

using -g or --global installs it as a global package.

javascript: Disable Text Select

Just use this css method:

body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

You can find the same answer here: How to disable text selection highlighting using CSS?

How can I create an MSI setup?

You can use Wix (which is free) to create an MSI installation package.

WiX Tutorial - Creating an Installer MSI with Wix

Capturing Groups From a Grep RegEx

if you have bash, you can use extended globbing

shopt -s extglob
shopt -s nullglob
shopt -s nocaseglob
for file in +([0-9])_+([a-z])_+([a-z0-9]).jpg
do
   IFS="_"
   set -- $file
   echo "This is your captured output : $2"
done

or

ls +([0-9])_+([a-z])_+([a-z0-9]).jpg | while read file
do
   IFS="_"
   set -- $file
   echo "This is your captured output : $2"
done

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

Get value (String) of ArrayList<ArrayList<String>>(); in Java

listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);

You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");

ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");

collection.Add(listOfSomething1);    
collection.Add(listOfSomething2);

How to set width of a div in percent in JavaScript?

jQuery way -

$("#id").width('30%');

What's the easiest way to call a function every 5 seconds in jQuery?

you could register an interval on the page using setInterval, ie:

setInterval(function(){ 
    //code goes here that will be run every 5 seconds.    
}, 5000);

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

jQuery hide and show toggle div with plus and minus icon

Here is a quick edit of Enve's answer. I do like roXor's solution, but background images are not necessary. And everbody seems to forgot a preventDefault as well.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".slidingDiv").hide();_x000D_
_x000D_
  $('.show_hide').click(function(e) {_x000D_
    $(".slidingDiv").slideToggle("fast");_x000D_
    var val = $(this).text() == "-" ? "+" : "-";_x000D_
    $(this).hide().text(val).fadeIn("fast");_x000D_
    e.preventDefault();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" class="show_hide">+</a>_x000D_
_x000D_
<div class="slidingDiv">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta._x000D_
    Mauris massa. Vestibulum lacinia arcu eget nulla. </p>_x000D_
_x000D_
  <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis._x000D_
    Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Absolute vs relative URLs

A URL that starts with the URL scheme and scheme specific part (http://, https://, ftp://, etc.) is an absolute URL.

Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.

Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

#define GENERAL__GET_BITS_FROM_U8(source,lsb,msb) \
    ((uint8_t)((source) & \
        ((uint8_t)(((uint8_t)(0xFF >> ((uint8_t)(7-((uint8_t)(msb) & 7))))) & \
             ((uint8_t)(0xFF << ((uint8_t)(lsb) & 7)))))))

#define GENERAL__GET_BITS_FROM_U16(source,lsb,msb) \
    ((uint16_t)((source) & \
        ((uint16_t)(((uint16_t)(0xFFFF >> ((uint8_t)(15-((uint8_t)(msb) & 15))))) & \
            ((uint16_t)(0xFFFF << ((uint8_t)(lsb) & 15)))))))

#define GENERAL__GET_BITS_FROM_U32(source,lsb,msb) \
    ((uint32_t)((source) & \
        ((uint32_t)(((uint32_t)(0xFFFFFFFF >> ((uint8_t)(31-((uint8_t)(msb) & 31))))) & \
            ((uint32_t)(0xFFFFFFFF << ((uint8_t)(lsb) & 31)))))))

How do I remove all null and empty string values from an object?

function removeAllBlankOrNull(JsonObj) {
    $.each(JsonObj, function(key, value) {
        if (value === "" || value === null) {
            delete JsonObj[key];
        } else if (typeof(value) === "object") {
            JsonObj[key] = removeAllBlankOrNull(value);
        }
    });
    return JsonObj;
}

Deletes all empty strings and null values recursively. Fiddle

How do I change the owner of a SQL Server database?

This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.

This should have nothing to do with the owner of the db.

undefined reference to boost::system::system_category() when compiling

Linking with a library that defines the missing symbol (-lboost_system) is the obvious solution, but in the particular case of Boost.System, a misfeature in the original design makes it use boost::system::generic_category() and boost::system::system_category() needlessly. Compiling with the flag -DBOOST_SYSTEM_NO_DEPRECATED disables that code and lets a number of programs compile without requiring -lboost_system (that link is of course still needed if you explicitly use some of the library's features).

Starting from Boost 1.66 and this commit, this behavior is now the default, so hopefully fewer and fewer users should need this answer.

As noticed by @AndrewMarshall, an alternative is to define BOOST_ERROR_CODE_HEADER_ONLY which enables a header-only version of the code. This was discouraged by Boost as it can break some functionality. However, since 1.69, header-only seems to have become the default, supposedly making this question obsolete.

Installing RubyGems in Windows

Installing Ruby

Go to http://rubyinstaller.org/downloads/

Make sure that you check "Add ruby ... to your PATH". enter image description here

Now you can use "ruby" in your "cmd".

If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193.

Installing Gem

install Development Kit in rubyinstaller. Make new folder such as C:\RubyDevKit and unzip.

Go to the devkit directory and type ruby dk.rb init to generate config.yml.

If you installed devkit for 1.9.3, I expect that the config.yml will be written as C:\Ruby193.

If not, please correct path to your ruby folders.

After reviewing the config.yml, you can finally type ruby dk.rb install.

Now you can use "gem" in your "cmd". It's done!

Convert row to column header for Pandas DataFrame,

It would be easier to recreate the data frame. This would also interpret the columns types from scratch.

headers = df.iloc[0]
new_df  = pd.DataFrame(df.values[1:], columns=headers)

Display PDF file inside my android application

I do not think that you can do this easily. you should consider this answer here:

How can I display a pdf document into a Webview?

basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)

'if' in prolog?

(  A == B ->
     writeln("ok")
;
     writeln("nok")
),

The else part is required

Trying to mock datetime.date.today(), but not working

Another option is to use https://github.com/spulec/freezegun/

Install it:

pip install freezegun

And use it:

from freezegun import freeze_time

@freeze_time("2012-01-01")
def test_something():

    from datetime import datetime
    print(datetime.now()) #  2012-01-01 00:00:00

    from datetime import date
    print(date.today()) #  2012-01-01

It also affects other datetime calls in method calls from other modules:

other_module.py:

from datetime import datetime

def other_method():
    print(datetime.now())    

main.py:

from freezegun import freeze_time

@freeze_time("2012-01-01")
def test_something():

    import other_module
    other_module.other_method()

And finally:

$ python main.py
# 2012-01-01

Generate random int value from 3 to 6

Lamak's answer as a function:

-- Create RANDBETWEEN function
-- Usage: SELECT dbo.RANDBETWEEN(0,9,RAND(CHECKSUM(NEWID())))
CREATE FUNCTION dbo.RANDBETWEEN(@minval TINYINT, @maxval TINYINT, @random NUMERIC(18,10))
RETURNS TINYINT
AS
BEGIN
  RETURN (SELECT CAST(((@maxval + 1) - @minval) * @random + @minval AS TINYINT))
END
GO

AngularJS - Passing data between pages

app.factory('persistObject', function () {

        var persistObject = [];

        function set(objectName, data) {
            persistObject[objectName] = data;
        }
        function get(objectName) {
            return persistObject[objectName];
        }

        return {
            set: set,
            get: get
        }
    });

Fill it with data like this

persistObject.set('objectName', data); 

Get the object data like this

persistObject.get('objectName'); 

Deleting a SQL row ignoring all foreign keys and constraints

I wanted to delete all records from both tables because it was all test data. I used SSMS GUI to temporarily disable a FK constraint, then I ran a DELETE query on both tables, and finally I re-enabled the FK constraint.

To disable the FK constraint:

  1. expand the database object [1]
  2. expand the dependant table object [2]
  3. expand the 'Keys' folder
  4. right click on the foreign key
  5. choose the 'Modify' option
  6. change the 'Enforce Foreign Key Constraint' option to 'No'
  7. close the 'Foreign Key Relationships' window
  8. close the table designer tab
  9. when prompted confirm save changes
  10. run necessary delete queries
  11. re-enable foreign key constraint the same way you just disabled it.

[1] in the 'Object Explorer' pane, can be accessed via the 'View' menu option, or key F8

[2] if you're not sure which table is the dependant one, you can check by right clicking the table in question and selecting the 'View Dependencies' option.

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

MySQL default datetime through phpmyadmin

I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..

CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());

Most efficient way to remove special characters from string

I wonder if a Regex-based replacement (possibly compiled) is faster. Would have to test that Someone has found this to be ~5 times slower.

Other than that, you should initialize the StringBuilder with an expected length, so that the intermediate string doesn't have to be copied around while it grows.

A good number is the length of the original string, or something slightly lower (depending on the nature of the functions inputs).

Finally, you can use a lookup table (in the range 0..127) to find out whether a character is to be accepted.

Cannot find or open the PDB file in Visual Studio C++ 2010

If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:

Use e.g.

D:\Visual Studio Projects\my_app\MyFile.pdb

Dont use e.g.

$(IntDir)\MyFile.pdb

in all the Sub-Projects !!!

= Compiler Param /Fd

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I had this problem and the suggestions above didn't help. What I found is that the add-migration reads the current state and creates a signature of the current model. You must modify your model before modifying. So the sequence is.

  1. Modify model
  2. run add-migration

I did the opposite and added the migration before modifying my model (which was empty, so I added the new columns) and then ran my code.

Hope this helps.

Stylesheet not updating

I had a similar problem, made all the more infuriating by simply being very SLOW to update. I couldn't get my changes to take effect while working on the site to save my life (trying all manner of clearing my browser cache and cookies), but if I came back to the site later in the day or opened another browser, there they were.

I also solved the problem by disabling the Supercacher software at my host's cpanel (Siteground). You can also use the "flush" button for individual directories to test if that's it before disabling.

Disable mouse scroll wheel zoom on embedded Google Maps

I just register one account on developers.google.com and get a token for call a Maps API, and just disable that like this (scrollwheel: false):

    var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('container_google_maps'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 8,
            scrollwheel: false
        });
    }

How to add 'libs' folder in Android Studio?

also, to get the right arrow, right click and "Add as Library".enter image description here

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

How does paintComponent work?

The (very) short answer to your question is that paintComponent is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.

There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent is called internally when it is determined that that operation is necessary.

I've worked with Swing for many years, and I don't think I've ever called paintComponent directly, or even seen it called directly from something else. The closest I've come is using the repaint() methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent methods downstream.

In my experience, paintComponent is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

Copy a variable's value into another

Most of the answers here are using built-in methods or using libraries/frameworks. This simple method should work fine:

function copy(x) {
    return JSON.parse( JSON.stringify(x) );
}

// Usage
var a = 'some';
var b = copy(a);
a += 'thing';

console.log(b); // "some"

var c = { x: 1 };
var d = copy(c);
c.x = 2;

console.log(d); // { x: 1 }

Adding multiple columns AFTER a specific column in MySQL

One possibility would be to not bother about reordering the columns in the table and simply modify it by add the columns. Then, create a view which has the columns in the order you want -- assuming that the order is truly important. The view can be easily changed to reflect any ordering that you want. Since I can't imagine that the order would be important for programmatic applications, the view should suffice for those manual queries where it might be important.

How to use clock() in C++

#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"

Python memory leaks

Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.

How to perform Join between multiple tables in LINQ lambda

take look at this sample code from my project

public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
    IEnumerable<Letter> allDepartmentLetters =
        from allLetter in LetterService.GetAllLetters()
        join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
        from user in usersGroup.DefaultIfEmpty()// here is the tricky part
        join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
        where allDepartment.ID == departmentId
        select allLetter;

    return allDepartmentLetters.ToArray();
}

in this code I joined 3 tables and I spited join condition from where clause

note: the Services classes are just warped(encapsulate) the database operations

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

How to remove \xa0 from string in Python?

I end up here while googling for the problem with not printable character. I use MySQL UTF-8 general_ci and deal with polish language. For problematic strings I have to procced as follows:

text=text.replace('\xc2\xa0', ' ')

It is just fast workaround and you probablly should try something with right encoding setup.

Auto line-wrapping in SVG text

The following code is working fine. Run the code snippet what it does.

Maybe it can be cleaned up or make it automatically work with all text tags in SVG.

_x000D_
_x000D_
function svg_textMultiline() {_x000D_
_x000D_
  var x = 0;_x000D_
  var y = 20;_x000D_
  var width = 360;_x000D_
  var lineHeight = 10;_x000D_
  _x000D_
  _x000D_
_x000D_
  /* get the text */_x000D_
  var element = document.getElementById('test');_x000D_
  var text = element.innerHTML;_x000D_
_x000D_
  /* split the words into array */_x000D_
  var words = text.split(' ');_x000D_
  var line = '';_x000D_
_x000D_
  /* Make a tspan for testing */_x000D_
  element.innerHTML = '<tspan id="PROCESSING">busy</tspan >';_x000D_
_x000D_
  for (var n = 0; n < words.length; n++) {_x000D_
    var testLine = line + words[n] + ' ';_x000D_
    var testElem = document.getElementById('PROCESSING');_x000D_
    /*  Add line in testElement */_x000D_
    testElem.innerHTML = testLine;_x000D_
    /* Messure textElement */_x000D_
    var metrics = testElem.getBoundingClientRect();_x000D_
    testWidth = metrics.width;_x000D_
_x000D_
    if (testWidth > width && n > 0) {_x000D_
      element.innerHTML += '<tspan x="0" dy="' + y + '">' + line + '</tspan>';_x000D_
      line = words[n] + ' ';_x000D_
    } else {_x000D_
      line = testLine;_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  element.innerHTML += '<tspan x="0" dy="' + y + '">' + line + '</tspan>';_x000D_
  document.getElementById("PROCESSING").remove();_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
svg_textMultiline();
_x000D_
body {_x000D_
  font-family: arial;_x000D_
  font-size: 20px;_x000D_
}_x000D_
svg {_x000D_
  background: #dfdfdf;_x000D_
  border:1px solid #aaa;_x000D_
}_x000D_
svg text {_x000D_
  fill: blue;_x000D_
  stroke: red;_x000D_
  stroke-width: 0.3;_x000D_
  stroke-linejoin: round;_x000D_
  stroke-linecap: round;_x000D_
}
_x000D_
<svg height="300" width="500" xmlns="http://www.w3.org/2000/svg" version="1.1">_x000D_
_x000D_
  <text id="test" y="0">GIETEN - Het college van Aa en Hunze is in de fout gegaan met het weigeren van een zorgproject in het failliete hotel Braams in Gieten. Dat stelt de PvdA-fractie in een brief aan het college. De partij wil opheldering over de kwestie en heeft schriftelijke_x000D_
    vragen ingediend. Verkeerde route De PvdA vindt dat de gemeenteraad eerst gepolst had moeten worden, voordat het college het plan afwees. "Volgens ons is de verkeerde route gekozen", zegt PvdA-raadslid Henk Santes.</text>_x000D_
_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How many threads is too many?

This question has been discussed quite thoroughly and I didn't get a chance to read all the responses. But here's few things to take into consideration while looking at the upper limit on number of simultaneous threads that can co-exist peacefully in a given system.

  1. Thread Stack Size : In Linux the default thread stack size is 8MB (you can use ulimit -a to find it out).
  2. Max Virtual memory that a given OS variant supports. Linux Kernel 2.4 supports a memory address space of 2 GB. with Kernel 2.6 , I a bit bigger (3GB )
  3. [1] shows the calculations for the max number of threads per given Max VM Supported. For 2.4 it turns out to be about 255 threads. for 2.6 the number is a bit larger.
  4. What kindda kernel scheduler you have . Comparing Linux 2.4 kernel scheduler with 2.6 , the later gives you a O(1) scheduling with no dependence upon number of tasks existing in a system while first one is more of a O(n). So also the SMP Capabilities of the kernel schedule also play a good role in max number of sustainable threads in a system.

Now you can tune your stack size to incorporate more threads but then you have to take into account the overheads of thread management(creation/destruction and scheduling). You can enforce CPU Affinity to a given process as well as to a given thread to tie them down to specific CPUs to avoid thread migration overheads between the CPUs and avoid cold cash issues.

Note that one can create thousands of threads at his/her wish , but when Linux runs out of VM it just randomly starts killing processes (thus threads). This is to keep the utility profile from being maxed out. (The utility function tells about system wide utility for a given amount of resources. With a constant resources in this case CPU Cycles and Memory, the utility curve flattens out with more and more number of tasks ).

I am sure windows kernel scheduler also does something of this sort to deal with over utilization of the resources

[1] http://adywicaksono.wordpress.com/2007/07/10/i-can-not-create-more-than-255-threads-on-linux-what-is-the-solutions/

MySQL error code: 1175 during UPDATE in MySQL Workbench

True, this is pointless for the most examples. But finally, I came to the following statement and it works fine:

update tablename  set column1 = '' where tablename .id = (select id from tablename2 where tablename2.column2 = 'xyz');

About the Full Screen And No Titlebar from manifest

In AndroidManifest.xml, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"in application tag.

Individual activities can override the default by setting their own theme attributes.

Read files from a Folder present in project

I have a C# project (Windows Console Application). I have created a folder named Images inside project. There is one ico file called MyIcon.ico. I accessed MyIcon.ico inside Images folder like below.

this.Icon = new Icon(@"../../Images/MyIcon.ico");

How to serialize object to CSV file?

For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.

How to style the option of an html "select" element?

No, it's not possible, as the styling for these elements is handled by the user's OS. MSDN will answer your question here:

Except for background-color and color, style settings applied through the style object for the option element are ignored.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

jquery: get id from class selector

When you add a click event, this returns the element that has been clicked. So you can just use this.id;

$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/

IIS w3svc error

In my case, IIS suddenly stoped working, and after that Windows process activation service was unable to restart.

The solution to fix this was:

  1. Find WAS service in the services tab of windows task manager
  2. In context menu choose Go to process
  3. Kill process (its name will be svchost.exe)
  4. Restart Windows process activation service

Hope it will be usefull.

Error loading the SDK when Eclipse starts

Copy the default devices.xml file from : /home/user/android-sdk/tools/lib/devices.xml

and paste it in the below paths: /android-sdk/system-images/android-22/android-wear/armeabi-v7a/ and /android-sdk/system-images/android-22/android-wear/x86/

This is a alternative solution, however, before replacing the devices.xml, take backup of the existing devices.xml file in these folders.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

console.log timestamps in Chrome?

Try this:

console.logCopy = console.log.bind(console);

console.log = function(data)
{
    var currentDate = '[' + new Date().toUTCString() + '] ';
    this.logCopy(currentDate, data);
};



Or this, in case you want a timestamp:

console.logCopy = console.log.bind(console);

console.log = function(data)
{
    var timestamp = '[' + Date.now() + '] ';
    this.logCopy(timestamp, data);
};



To log more than one thing and in a nice way (like object tree representation):

console.logCopy = console.log.bind(console);

console.log = function()
{
    if (arguments.length)
    {
        var timestamp = '[' + Date.now() + '] ';
        this.logCopy(timestamp, arguments);
    }
};



With format string (JSFiddle)

console.logCopy = console.log.bind(console);

console.log = function()
{
    // Timestamp to prepend
    var timestamp = new Date().toJSON();

    if (arguments.length)
    {
        // True array copy so we can call .splice()
        var args = Array.prototype.slice.call(arguments, 0);

        // If there is a format string then... it must
        // be a string
        if (typeof arguments[0] === "string")
        {
            // Prepend timestamp to the (possibly format) string
            args[0] = "%o: " + arguments[0];

            // Insert the timestamp where it has to be
            args.splice(1, 0, timestamp);

            // Log the whole array
            this.logCopy.apply(this, args);
        }
        else
        { 
            // "Normal" log
            this.logCopy(timestamp, args);
        }
    }
};


Outputs with that:

Sample output

P.S.: Tested in Chrome only.

P.P.S.: Array.prototype.slice is not perfect here for it would be logged as an array of objects rather than a series those of.

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

I can not find my.cnf on my windows computer

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I had this same problem. I had set Project A's "Platform Target" ("Project A"(Right Click)->Properties->Build->"Platform Target") to x86 but kept Project B's at "Any CPU". Setting Project B's to "x86" fixed this.

What's the difference between an id and a class?

Any element can have a class or an id.

A class is used to reference a certain type of display, for example you may have a css class for a div that represents the answer to this question. As there will be many answers, multiple divs would need the same styling and you would use a class.

An id refers to only a single element, for example the related section at the right may have styling specific to it not reused elsewhere, it would use an id.

Technically you can use classes for all of it, or split them up logically. You can not, however, reuse id's for multiple elements.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

As mentioned in documentation:

Android Studio automatically adds this attribute when you click Run

So, to be able to install your apk with adb install <path to apk file> you need to assemble build from terminal: ./gradlew assembleDebug and install with adb. Or just run ./gradlew installDebug to build and install on the device simultaneously.

What version of JBoss I am running?

Use the following command from Linux

find $JBOSS_HOME -name run.sh -exec {} -V \; | grep '^JBoss'

Delete all the queues from RabbitMQ?

You need not reset rabbitmq server to delete non-durable queues. Simply stop the server and start again and it will remove all the non-durable queues available.

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

How to add property to a class dynamically?

Here is the simple example to create property object programmatically.

#!/usr/bin/python3

class Counter:
    def __init__(self):
        cls = self.__class__
        self._count = 0
        cls.count = self.count_ref()

    def count_get(self):
        print(f'count_get: {self._count}')
        return self._count

    def count_set(self, value):
        self._count = value
        print(f'count_set: {self._count}')

    def count_del(self):
        print(f'count_del: {self._count}')

    def count_ref(self):
        cls = self.__class__
        return property(fget=cls.count_get, fset=cls.count_set, fdel=cls.count_del)

counter = Counter()

counter.count
for i in range(5):
    counter.count = i
del counter.count

'''
output
======
count_get: 0
count_set: 0
count_set: 1
count_set: 2
count_set: 3
count_set: 4
count_del: 4
'''

Is there an equivalent of CSS max-width that works in HTML emails?

The short answer: no.

The long answer:

Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.

It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

How do I prevent the padding property from changing width or height in CSS?

just change your div width to 160px if you have a padding of 20px it adds 40px extra to the width of your div so you need to subtract 40px from the width in order to keep your div looking normal and not distorted with extra width on it and your text all messed up.

How to iterate over a JavaScript object?

Yes. You can loop through an object using for loop. Here is an example

_x000D_
_x000D_
var myObj = {_x000D_
    abc: 'ABC',_x000D_
    bca: 'BCA',_x000D_
    zzz: 'ZZZ',_x000D_
    xxx: 'XXX',_x000D_
    ccc: 'CCC',_x000D_
}_x000D_
_x000D_
var k = Object.keys (myObj);_x000D_
for (var i = 0; i < k.length; i++) {_x000D_
    console.log (k[i] + ": " + myObj[k[i]]);_x000D_
}
_x000D_
_x000D_
_x000D_

NOTE: the example mentioned above will only work in IE9+. See Objec.keys browser support here.

Checking Maven Version

You need to add path to svn.exe file to system environment, variable PATH, after that you can run command mvn from any folder. You can do it from command line(cmd.exe) like this, for example:

set PATH=%PATH%;C:\maven\bin

Or you can got to the folder where mvn.exe is, and run your command there.

And you need not mvn -version, but mvn --version parameter.

Multipart forms from C# client

I needed to simulate a browser login to a website to get a login cookie, and the login form was multipart/form-data.

I took some clues from the other answers here, and then tried to get my own scenario working. It took a bit of frustrating trial and error before it worked right, but here is the code:

    public static class WebHelpers
    {
        /// <summary>
        /// Post the data as a multipart form
        /// </summary>
       public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, string> values)
       {
           string formDataBoundary = "---------------------------" + WebHelpers.RandomHexDigits(12);
           string contentType = "multipart/form-data; boundary=" + formDataBoundary;

           string formData = WebHelpers.MakeMultipartForm(values, formDataBoundary);
           return WebHelpers.PostForm(postUrl, userAgent, contentType, formData);
       }

        /// <summary>
        /// Post a form
        /// </summary>
        public static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, string formData)
        {
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            // Add these, as we're doing a POST
            request.Method = "POST";
            request.ContentType = contentType;
            request.UserAgent = userAgent;
            request.CookieContainer = new CookieContainer();

            // We need to count how many bytes we're sending. 
            byte[] postBytes = Encoding.UTF8.GetBytes(formData);
            request.ContentLength = postBytes.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                // Push it out there
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();
            }

            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// Generate random hex digits 
        /// </summary>
        public static string RandomHexDigits(int count)
        {
            Random random = new Random();
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                int digit = random.Next(16);
                result.AppendFormat("{0:x}", digit);
            }

            return result.ToString();
        }

        /// <summary>
        /// Turn the key and value pairs into a multipart form
        /// </summary>
        private static string MakeMultipartForm(Dictionary<string, string> values, string boundary)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var pair in values)
            {
                sb.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, pair.Key, pair.Value);
            }

            sb.AppendFormat("--{0}--\r\n", boundary);

            return sb.ToString();    
        }
    }
}

It doesn't handle file data, just form since that's all that I needed. I called like this:

    try
    {
        using (HttpWebResponse response = WebHelpers.MultipartFormDataPost(postUrl, UserAgentString, this.loginForm)) 
        {
            if (response != null)
            {
                Cookie loginCookie = response.Cookies["logincookie"];
                .....

How to examine processes in OS X's Terminal?

You can just use top It will display everything running on your OSX

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

How to declare a global variable in JavaScript

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

Failed to execute 'createObjectURL' on 'URL':

This error is caused because the function createObjectURL is deprecated for Google Chrome

I changed this:

video.src=vendorUrl.createObjectURL(stream);
video.play();

to this:

video.srcObject=stream;
video.play();

This worked for me.

iPhone: How to get current milliseconds?

let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)

Using RegEx in SQL Server

SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'

Or some other expression instead of A-Z

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

Pass by Reference / Value in C++

When passing by value:

void func(Object o);

and then calling

func(a);

you will construct an Object on the stack, and within the implementation of func it will be referenced by o. This might still be a shallow copy (the internals of a and o might point to the same data), so a might be changed. However if o is a deep copy of a, then a will not change.

When passing by reference:

void func2(Object& o);

and then calling

func2(a);

you will only be giving a new way to reference a. "a" and "o" are two names for the same object. Changing o inside func2 will make those changes visible to the caller, who knows the object by the name "a".

Using Selenium Web Driver to retrieve value of a HTML input

For python bindings it will be :

element.get_attribute('value')

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

How to select rows from a DataFrame based on column values

There are several ways to select rows from a Pandas dataframe:

  1. Boolean indexing (df[df['col'] == value] )
  2. Positional indexing (df.iloc[...])
  3. Label indexing (df.xs(...))
  4. df.query(...) API

Below I show you examples of each, with advice when to use certain techniques. Assume our criterion is column 'A' == 'foo'

(Note on performance: For each base type, we can keep things simple by using the Pandas API or we can venture outside the API, usually into NumPy, and speed things up.)


Setup

The first thing we'll need is to identify a condition that will act as our criterion for selecting rows. We'll start with the OP's case column_name == some_value, and include some other common use cases.

Borrowing from @unutbu:

import pandas as pd, numpy as np

df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

1. Boolean indexing

... Boolean indexing requires finding the true value of each row's 'A' column being equal to 'foo', then using those truth values to identify which rows to keep. Typically, we'd name this series, an array of truth values, mask. We'll do so here as well.

mask = df['A'] == 'foo'

We can then use this mask to slice or index the data frame

df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

This is one of the simplest ways to accomplish this task and if performance or intuitiveness isn't an issue, this should be your chosen method. However, if performance is a concern, then you might want to consider an alternative way of creating the mask.


2. Positional indexing

Positional indexing (df.iloc[...]) has its use cases, but this isn't one of them. In order to identify where to slice, we first need to perform the same boolean analysis we did above. This leaves us performing one extra step to accomplish the same task.

mask = df['A'] == 'foo'
pos = np.flatnonzero(mask)
df.iloc[pos]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

3. Label indexing

Label indexing can be very handy, but in this case, we are again doing more work for no benefit

df.set_index('A', append=True, drop=False).xs('foo', level=1)

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

4. df.query() API

pd.DataFrame.query is a very elegant/intuitive way to perform this task, but is often slower. However, if you pay attention to the timings below, for large data, the query is very efficient. More so than the standard approach and of similar magnitude as my best suggestion.

df.query('A == "foo"')

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

My preference is to use the Boolean mask

Actual improvements can be made by modifying how we create our Boolean mask.

mask alternative 1 Use the underlying NumPy array and forgo the overhead of creating another pd.Series

mask = df['A'].values == 'foo'

I'll show more complete time tests at the end, but just take a look at the performance gains we get using the sample data frame. First, we look at the difference in creating the mask

%timeit mask = df['A'].values == 'foo'
%timeit mask = df['A'] == 'foo'

5.84 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
166 µs ± 4.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Evaluating the mask with the NumPy array is ~ 30 times faster. This is partly due to NumPy evaluation often being faster. It is also partly due to the lack of overhead necessary to build an index and a corresponding pd.Series object.

Next, we'll look at the timing for slicing with one mask versus the other.

mask = df['A'].values == 'foo'
%timeit df[mask]
mask = df['A'] == 'foo'
%timeit df[mask]

219 µs ± 12.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
239 µs ± 7.03 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The performance gains aren't as pronounced. We'll see if this holds up over more robust testing.


mask alternative 2 We could have reconstructed the data frame as well. There is a big caveat when reconstructing a dataframe—you must take care of the dtypes when doing so!

Instead of df[mask] we will do this

pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

If the data frame is of mixed type, which our example is, then when we get df.values the resulting array is of dtype object and consequently, all columns of the new data frame will be of dtype object. Thus requiring the astype(df.dtypes) and killing any potential performance gains.

%timeit df[m]
%timeit pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

216 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.43 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

However, if the data frame is not of mixed type, this is a very useful way to do it.

Given

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

d1

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

%%timeit
mask = d1['A'].values == 7
d1[mask]

179 µs ± 8.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Versus

%%timeit
mask = d1['A'].values == 7
pd.DataFrame(d1.values[mask], d1.index[mask], d1.columns)

87 µs ± 5.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

We cut the time in half.


mask alternative 3

@unutbu also shows us how to use pd.Series.isin to account for each element of df['A'] being in a set of values. This evaluates to the same thing if our set of values is a set of one value, namely 'foo'. But it also generalizes to include larger sets of values if needed. Turns out, this is still pretty fast even though it is a more general solution. The only real loss is in intuitiveness for those not familiar with the concept.

mask = df['A'].isin(['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

However, as before, we can utilize NumPy to improve performance while sacrificing virtually nothing. We'll use np.in1d

mask = np.in1d(df['A'].values, ['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing

I'll include other concepts mentioned in other posts as well for reference.

Code Below

Each column in this table represents a different length data frame over which we test each function. Each column shows relative time taken, with the fastest function given a base index of 1.0.

res.div(res.min())

                         10        30        100       300       1000      3000      10000     30000
mask_standard         2.156872  1.850663  2.034149  2.166312  2.164541  3.090372  2.981326  3.131151
mask_standard_loc     1.879035  1.782366  1.988823  2.338112  2.361391  3.036131  2.998112  2.990103
mask_with_values      1.010166  1.000000  1.005113  1.026363  1.028698  1.293741  1.007824  1.016919
mask_with_values_loc  1.196843  1.300228  1.000000  1.000000  1.038989  1.219233  1.037020  1.000000
query                 4.997304  4.765554  5.934096  4.500559  2.997924  2.397013  1.680447  1.398190
xs_label              4.124597  4.272363  5.596152  4.295331  4.676591  5.710680  6.032809  8.950255
mask_with_isin        1.674055  1.679935  1.847972  1.724183  1.345111  1.405231  1.253554  1.264760
mask_with_in1d        1.000000  1.083807  1.220493  1.101929  1.000000  1.000000  1.000000  1.144175

You'll notice that the fastest times seem to be shared between mask_with_values and mask_with_in1d.

res.T.plot(loglog=True)

Enter image description here

Functions

def mask_standard(df):
    mask = df['A'] == 'foo'
    return df[mask]

def mask_standard_loc(df):
    mask = df['A'] == 'foo'
    return df.loc[mask]

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_values_loc(df):
    mask = df['A'].values == 'foo'
    return df.loc[mask]

def query(df):
    return df.query('A == "foo"')

def xs_label(df):
    return df.set_index('A', append=True, drop=False).xs('foo', level=-1)

def mask_with_isin(df):
    mask = df['A'].isin(['foo'])
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

Testing

res = pd.DataFrame(
    index=[
        'mask_standard', 'mask_standard_loc', 'mask_with_values', 'mask_with_values_loc',
        'query', 'xs_label', 'mask_with_isin', 'mask_with_in1d'
    ],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

for j in res.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in res.index:a
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        res.at[i, j] = timeit(stmt, setp, number=50)

Special Timing

Looking at the special case when we have a single non-object dtype for the entire data frame.

Code Below

spec.div(spec.min())

                     10        30        100       300       1000      3000      10000     30000
mask_with_values  1.009030  1.000000  1.194276  1.000000  1.236892  1.095343  1.000000  1.000000
mask_with_in1d    1.104638  1.094524  1.156930  1.072094  1.000000  1.000000  1.040043  1.027100
reconstruct       1.000000  1.142838  1.000000  1.355440  1.650270  2.222181  2.294913  3.406735

Turns out, reconstruction isn't worth it past a few hundred rows.

spec.T.plot(loglog=True)

Enter image description here

Functions

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

def reconstruct(df):
    v = df.values
    mask = np.in1d(df['A'].values, ['foo'])
    return pd.DataFrame(v[mask], df.index[mask], df.columns)

spec = pd.DataFrame(
    index=['mask_with_values', 'mask_with_in1d', 'reconstruct'],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

Testing

for j in spec.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in spec.index:
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        spec.at[i, j] = timeit(stmt, setp, number=50)

How to change an image on click using CSS alone?

some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:

<style>
.off{
    color:red;
}
.on{
    color:green;
}
</style>
<a href="" class="off" onclick="this.className='on';return false;">Foo</a>

using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.

Good Luck

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

PHP function overloading

It may be hackish to some, but I learned this way from how Cakephp does some functions and have adapted it because I like the flexibility it creates

The idea is you have different type of arguments, arrays, objects etc, then you detect what you were passed and go from there

function($arg1, $lastname) {
    if(is_array($arg1)){
        $lastname = $arg1['lastname'];
        $firstname = $arg1['firstname'];
    } else {
        $firstname = $arg1;
    }
    ...
}

How to shrink/purge ibdata1 file in MySQL

That ibdata1 isn't shrinking is a particularly annoying feature of MySQL. The ibdata1 file can't actually be shrunk unless you delete all databases, remove the files and reload a dump.

But you can configure MySQL so that each table, including its indexes, is stored as a separate file. In that way ibdata1 will not grow as large. According to Bill Karwin's comment this is enabled by default as of version 5.6.6 of MySQL.

It was a while ago I did this. However, to setup your server to use separate files for each table you need to change my.cnf in order to enable this:

[mysqld]
innodb_file_per_table=1

https://dev.mysql.com/doc/refman/5.6/en/innodb-file-per-table-tablespaces.html

As you want to reclaim the space from ibdata1 you actually have to delete the file:

  1. Do a mysqldump of all databases, procedures, triggers etc except the mysql and performance_schema databases
  2. Drop all databases except the above 2 databases
  3. Stop mysql
  4. Delete ibdata1 and ib_log files
  5. Start mysql
  6. Restore from dump

When you start MySQL in step 5 the ibdata1 and ib_log files will be recreated.

Now you're fit to go. When you create a new database for analysis, the tables will be located in separate ibd* files, not in ibdata1. As you usually drop the database soon after, the ibd* files will be deleted.

http://dev.mysql.com/doc/refman/5.1/en/drop-database.html

You have probably seen this:
http://bugs.mysql.com/bug.php?id=1341

By using the command ALTER TABLE <tablename> ENGINE=innodb or OPTIMIZE TABLE <tablename> one can extract data and index pages from ibdata1 to separate files. However, ibdata1 will not shrink unless you do the steps above.

Regarding the information_schema, that is not necessary nor possible to drop. It is in fact just a bunch of read-only views, not tables. And there are no files associated with the them, not even a database directory. The informations_schema is using the memory db-engine and is dropped and regenerated upon stop/restart of mysqld. See https://dev.mysql.com/doc/refman/5.7/en/information-schema.html.

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Create zip file and ignore directory structure

Use the -j option:

   -j     Store  just the name of a saved file (junk the path), and do not
          store directory names. By default, zip will store the full  path
          (relative to the current path).

How to retrieve Jenkins build parameters using the Groovy API?

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

Getting the index of the returned max or min item using max()/min() on a list

I was also interested in this and compared some of the suggested solutions using perfplot (a pet project of mine).

Turns out that numpy's argmin,

numpy.argmin(x)

is the fastest method for large enough lists, even with the implicit conversion from the input list to a numpy.array.

enter image description here


Code for generating the plot:

import numpy
import operator
import perfplot


def min_enumerate(a):
    return min(enumerate(a), key=lambda x: x[1])[0]


def min_enumerate_itemgetter(a):
    min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))
    return min_index


def getitem(a):
    return min(range(len(a)), key=a.__getitem__)


def np_argmin(a):
    return numpy.argmin(a)


perfplot.show(
    setup=lambda n: numpy.random.rand(n).tolist(),
    kernels=[
        min_enumerate,
        min_enumerate_itemgetter,
        getitem,
        np_argmin,
        ],
    n_range=[2**k for k in range(15)],
    logx=True,
    logy=True,
    )

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

How to set a bitmap from resource

Try this

This is from sdcard

ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);

This is from resources

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

Installing Oracle Instant Client

The directions state:

  1. Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
  2. Unzip the packages into a single directory such as "instantclient".
  3. Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
  4. Start your application and enjoy.

Suggest extracting/unzipping into a new directory. They've suggested instantclient, but you can name the directory anything you like. Name it C:\OracleInstantClient\ if you choose.

Then in Step 3, open a Windows Command Prompt. Type:

PATH C:\OracleInstantClient; %PATH%`

That's all there is to it!

How to pick an image from gallery (SD Card) for my app?

call chooseImage method like-

public void chooseImage(ImageView v)
{
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, SELECT_PHOTO);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(imageReturnedIntent != null)
    {
        Uri selectedImage = imageReturnedIntent.getData();
    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK)
        {
            Bitmap datifoto = null;
            temp.setImageBitmap(null);
            Uri picUri = null;
            picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
             if(picUri !=null){
               try {
                   datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(),                                 picUri);
                   temp.setImageBitmap(datifoto);
               } catch (FileNotFoundException e) {
                  throw new RuntimeException(e);
               } catch (IOException e) {
                  throw new RuntimeException(e);
               } catch (OutOfMemoryError e) {
                Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
            }

        }
        }
        break;

}
    }
    else
    {
        //Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
    }
}

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

Keep values selected after form submission

To avoid many if-else structures, let JavaScript do the trick automatically:

<select name="name" id="name">
   <option value="a">a</option>
   <option value="b">b</option>
</select>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>

<select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>
</select>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>

How do I check if a list is empty?

Here are a few ways you can check if a list is empty:

a = [] #the list

1) The pretty simple pythonic way:

if not a:
    print("a is empty")

In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False. One could simply treat the list as a predicate (returning a Boolean value). And a True value would indicate that it's non-empty.

2) A much explicit way: using the len() to find the length and check if it equals to 0:

if len(a) == 0:
    print("a is empty")

3) Or comparing it to an anonymous empty list:

if a == []:
    print("a is empty")

4) Another yet silly way to do is using exception and iter():

try:
    next(iter(a))
    # list has elements
except StopIteration:
    print("Error: a is empty")

Java converting int to hex and back again

Hehe, curious. I think this is an "intentianal bug", so to speak.

The underlying reason is how the Integer class is written. Basically, parseInt is "optimized" for positive numbers. When it parses the string, it builds the result cumulatively, but negated. Then it flips the sign of the end-result.

Example:

66 = 0x42

parsed like:

4*(-1) = -4
-4 * 16 = -64 (hex 4 parsed)

-64 - 2 = -66 (hex 2 parsed)

return -66 * (-1) = 66

Now, let's look at your example FFFF8000

16*(-1) = -16 (first F parsed)
-16*16 = -256 

-256 - 16 = -272 (second F parsed)
-272 * 16 = -4352 

-4352 - 16 = -4368 (third F parsed)
-4352 * 16 = -69888

-69888 - 16 = -69904 (forth F parsed)
-69904 * 16 = -1118464 

-1118464 - 8 = -1118472 (8 parsed)
-1118464 * 16 = -17895552 

-17895552 - 0 = -17895552 (first 0 parsed)
Here it blows up since -17895552 < -Integer.MAX_VALUE / 16 (-134217728). 
Attempting to execute the next logical step in the chain (-17895552 * 16)
would cause an integer overflow error.

Edit (addition): in order for the parseInt() to work "consistently" for -Integer.MAX_VALUE <= n <= Integer.MAX_VALUE, they would have had to implement logic to "rotate" when reaching -Integer.MAX_VALUE in the cumulative result, starting over at the max-end of the integer range and continuing downwards from there. Why they did not do this, one would have to ask Josh Bloch or whoever implemented it in the first place. It might just be an optimization.

However,

Hex=Integer.toHexString(Integer.MAX_VALUE);
System.out.println(Hex);
System.out.println(Integer.parseInt(Hex.toUpperCase(), 16));

works just fine, for just this reason. In the sourcee for Integer you can find this comment.

// Accumulating negatively avoids surprises near MAX_VALUE

Timing Delays in VBA

If you are in Excel VBA you can use the following.

Application.Wait(Now + TimeValue("0:00:01"))

(The time string should look like H:MM:SS.)

Laravel 5: Display HTML with Blade

For laravel 5

{!!html_entity_decode($text)!!}

Figured out through this link, see RachidLaasri answer

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Is there a way to view past mysql queries with phpmyadmin?

You just need to click on console at the bottom of the screen in phpMyAdmin and you will get the Executed history:

enter image description here

How to read the output from git diff?

It's unclear from your question which part of the diffs you find confusing: the actually diff, or the extra header information git prints. Just in case, here's a quick overview of the header.

The first line is something like diff --git a/path/to/file b/path/to/file - obviously it's just telling you what file this section of the diff is for. If you set the boolean config variable diff.mnemonic prefix, the a and b will be changed to more descriptive letters like c and w (commit and work tree).

Next, there are "mode lines" - lines giving you a description of any changes that don't involve changing the content of the file. This includes new/deleted files, renamed/copied files, and permissions changes.

Finally, there's a line like index 789bd4..0afb621 100644. You'll probably never care about it, but those 6-digit hex numbers are the abbreviated SHA1 hashes of the old and new blobs for this file (a blob is a git object storing raw data like a file's contents). And of course, the 100644 is the file's mode - the last three digits are obviously permissions; the first three give extra file metadata information (SO post describing that).

After that, you're on to standard unified diff output (just like the classic diff -U). It's split up into hunks - a hunk is a section of the file containing changes and their context. Each hunk is preceded by a pair of --- and +++ lines denoting the file in question, then the actual diff is (by default) three lines of context on either side of the - and + lines showing the removed/added lines.

Check OS version in Swift?

let osVersion = NSProcessInfo.processInfo().operatingSystemVersion
let versionString = osVersion.majorVersion.description + "." + osVersion.minorVersion.description + "." + osVersion.patchVersion.description
print(versionString)

Can I multiply strings in Java to repeat sequences?

Google Guava provides another way to do this with Strings#repeat():

String repeated = Strings.repeat("pete and re", 42);

How to send objects through bundle

Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.

The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:

1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.

2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.

3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.

Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.

Best practices for catching and re-throwing .NET exceptions

Actually, there are some situations which the throw statment will not preserve the StackTrace information. For example, in the code below:

try
{
  int i = 0;
  int j = 12 / i; // Line 47
  int k = j + 1;
}
catch
{
  // do something
  // ...
  throw; // Line 54
}

The StackTrace will indicate that line 54 raised the exception, although it was raised at line 47.

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at Program.WithThrowIncomplete() in Program.cs:line 54
   at Program.Main(String[] args) in Program.cs:line 106

In situations like the one described above, there are two options to preseve the original StackTrace:

Calling the Exception.InternalPreserveStackTrace

As it is a private method, it has to be invoked by using reflection:

private static void PreserveStackTrace(Exception exception)
{
  MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
    BindingFlags.Instance | BindingFlags.NonPublic);
  preserveStackTrace.Invoke(exception, null);
}

I has a disadvantage of relying on a private method to preserve the StackTrace information. It can be changed in future versions of .NET Framework. The code example above and proposed solution below was extracted from Fabrice MARGUERIE weblog.

Calling Exception.SetObjectData

The technique below was suggested by Anton Tykhyy as answer to In C#, how can I rethrow InnerException without losing stack trace question.

static void PreserveStackTrace (Exception e) 
{ 
  var ctx = new StreamingContext  (StreamingContextStates.CrossAppDomain) ; 
  var mgr = new ObjectManager     (null, ctx) ; 
  var si  = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; 

  e.GetObjectData    (si, ctx)  ; 
  mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData 
  mgr.DoFixups       ()         ; // ObjectManager calls SetObjectData 

  // voila, e is unmodified save for _remoteStackTraceString 
} 

Although, it has the advantage of relying in public methods only it also depends on the following exception constructor (which some exceptions developed by 3rd parties do not implement):

protected Exception(
    SerializationInfo info,
    StreamingContext context
)

In my situation, I had to choose the first approach, because the exceptions raised by a 3rd-party library I was using didn't implement this constructor.

"You have mail" message in terminal, os X

As inspiredlife explained, you can figure out whats happening using mail command.

If you don't want to delete bunch of unrelated / auto-generated messages one by one (like me), simply run the command below to get rid of all messages:

echo -n > /var/mail/yourusername

jQuery: Setting select list 'selected' based on text, failing strangely

If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:

    <select id="selectcountry">
    <option value="1">India</option>
    <option value="2">Ireland</option>
    </select>
    <script>
     var country_name ='India'
     $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
    </script>

Python - How to cut a string in Python?

You can use find()

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s[:s.find('&')]
'http://www.domain.com/?s=some'

Of course, if there is a chance that the searched for text will not be present then you need to write more lengthy code:

pos = s.find('&')
if pos != -1:
    s = s[:pos]

Whilst you can make some progress using code like this, more complex situations demand a true URL parser.

Is JavaScript's "new" keyword considered harmful?

The rationale behind not using the new keyword, is simple:

By not using it at all, you avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUI uses, is an example of how you can avoid the new keyword altogether"

var foo = function () {
    var pub= { };
    return pub;
}
var bar = foo();

Alternatively you could so this:

function foo() { }
var bar = new foo();

But by doing so you run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than you are used to it).

At The End Of The Day: It's about being defensive. Can you use the new statement? Yes. Does it make your code more dangerous? Yes.

If you have ever written C++, it's akin to setting pointers to NULL after you delete them.

How to get start and end of day in Javascript?

In MomentJs We can declare it like :

   const start = moment().format('YYYY-MM-DD 00:00:01');
   const end = moment().format('YYYY-MM-DD 23:59:59');

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

How to get the previous URL in JavaScript?

If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:

window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")

Then, in your new route, you can do the following to retrieve the previous URL:

window.history.state.prevUrl // your previous url

How to find out mySQL server ip address from phpmyadmin

As an alternative, since you know the hostname, resolve the database server IP via hostname from the web server.

http://php.net/manual/en/function.gethostbyname.php

Is there a performance difference between i++ and ++i in C?

A better answer is that ++i will sometimes be faster but never slower.

Everyone seems to be assuming that i is a regular built-in type such as int. In this case there will be no measurable difference.

However if i is complex type then you may well find a measurable difference. For i++ you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with ++it you can just return the final value.

Foo Foo::operator++()
{
  Foo oldFoo = *this; // copy existing value - could be slow
  // yadda yadda, do increment
  return oldFoo;
}

Another difference is that with ++i you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower.

A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using ++i instead of i++ where the outcome is not affected.

How do I upgrade to Python 3.6 with conda?

In the past, I have found it quite difficult to try to upgrade in-place.

Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda to create environments, this may be destructive because conda creates environments with hard-links inside your Anaconda/envs directory.

So if you use environments, you may first want to export your environments. After activating your environment, do something like:

conda env export > environment.yml

After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):

$ rm -rf ~/anaconda3/

and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:

$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh 

(see here for a more recent one),

and then executing it:

$ bash Anaconda3-4.3.0-Linux-x86_64.sh 

How to download dependencies in gradle

For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. enter image description here

Xcode Objective-C | iOS: delay function / NSTimer help?

I would like to add a bit the answer by Avner Barr. When using int64, it appears that when we surpass the 1.0 value, the function seems to delay differently. So I think at this point, we should use NSTimeInterval.

So, the final code is:

NSTimeInterval delayInSeconds = 0.05;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

//do your tasks here

});

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

How to send a “multipart/form-data” POST in Android with Volley

UPDATE 2015/08/26:

If you don't want to use deprecated HttpEntity, here is my working sample code (tested with ASP.Net WebAPI)

MultipartActivity.java

package com.example.volleyapp;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.volleyapp.BaseVolleyRequest;
import com.example.volleyapp.VolleySingleton;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class MultipartActivity extends Activity {

    final Context mContext = this;
    String mimeType;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String boundary = "apiclient-" + System.currentTimeMillis();
    String twoHyphens = "--";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024;

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

        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_action_file_attachment_light);
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        final byte[] bitmapData = byteArrayOutputStream.toByteArray();
        String url = "http://192.168.1.100/api/postfile";

        mimeType = "multipart/form-data;boundary=" + boundary;

        BaseVolleyRequest baseVolleyRequest = new BaseVolleyRequest(1, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public String getBodyContentType() {
                return mimeType;
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                dos = new DataOutputStream(bos);
                try {
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                            + "ic_action_file_attachment_light.png" + "\"" + lineEnd);
                    dos.writeBytes(lineEnd);
                    ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapData);
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

                    // send multipart form data necesssary after file data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    return bos.toByteArray();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return bitmapData;
            }
        };

        VolleySingleton.getInstance(mContext).addToRequestQueue(baseVolleyRequest);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_multipart, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

BaseVolleyRequest.java:

package com.example.volleyapp;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonSyntaxException;


public class BaseVolleyRequest extends Request<NetworkResponse> {

    private final Response.Listener<NetworkResponse> mListener;
    private final Response.ErrorListener mErrorListener;

    public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
        super(0, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    public BaseVolleyRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    @Override
    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        try {
            return Response.success(
                    response,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        } catch (Exception e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(NetworkResponse response) {
        mListener.onResponse(response);
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        return super.parseNetworkError(volleyError);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }
}

END OF UPDATE

This is my working sample code (only tested with small-size files):

public class FileUploadActivity extends Activity {

    private final Context mContext = this;
    HttpEntity httpEntity;

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

        Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            final byte[] bitmapdata = stream.toByteArray();
            String url = "http://10.0.2.2/api/fileupload";
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add binary body
            if (bitmapdata != null) {
                ContentType contentType = ContentType.create("image/png");
                String fileName = "ic_action_home.png";
                builder.addBinaryBody("file", bitmapdata, contentType, fileName);
                httpEntity = builder.build();

                MyRequest myRequest = new MyRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
                    @Override
                    public void onResponse(NetworkResponse response) {
                        try {                            
                            String jsonString = new String(response.data,
                                    HttpHeaderParser.parseCharset(response.headers));
                            Toast.makeText(mContext, jsonString, Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, error.toString(), Toast.LENGTH_SHORT).show();                        
                    }
                }) {
                    @Override
                    public String getBodyContentType() {
                        return httpEntity.getContentType().getValue();
                    }

                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        try {
                            httpEntity.writeTo(bos);
                        } catch (IOException e) {
                            VolleyLog.e("IOException writing to ByteArrayOutputStream");
                        }
                        return bos.toByteArray();
                    }
                };

                MySingleton.getInstance(this).addToRequestQueue(myRequest);
            }
        }
    }

    ...
}

public class MyRequest extends Request<NetworkResponse>

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Yes. If you have installed sp_who2k5 into your master database, you can simply run:

sp_who2k5 1,1

The resultset will include all the active transactions. The currently running backup(s) will contain the string "BACKUP" in the requestCommand field. The aptly named percentComplete field will give you the progress of the backup.

Note: sp_who2k5 should be a part of everyone's toolkit, it does a lot more than just this.

Remove Object from Array using JavaScript

There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)

Is there any boolean type in Oracle databases?

Just because nobody mentioned it yet: using RAW(1) also seems common practice.

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

Recommended way to embed PDF in HTML?

To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.

How to declare a global variable in React?

I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:

Carrying values between functions, on the same page

In your constructor, bind your setter:

this.setSomeVariable = this.setSomeVariable.bind(this);

Then declare a function just below your constructor:

setSomeVariable(propertyTextToAdd) {
    this.setState({
        myProperty: propertyTextToAdd
    });
}

When you want to set it, call this.setSomeVariable("some value");

(You might even be able to get away with this.state.myProperty = "some value";)

When you want to get it, call var myProp = this.state.myProperty;

Using alert(myProp); should give you some value .

Extra scaffolding method to carry values across pages/components

You can assign a model to this (technically this.stores), so you can then reference it with this.state:

import Reflux from 'reflux'
import Actions from '~/actions/actions`

class YourForm extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {
            someGlobalVariable: '',
        };
        this.listenables = Actions;
        this.baseState = {
            someGlobalVariable: '',
        };
    }

    onUpdateFields(name, value) {
        this.setState({
            [name]: value,
        });
    }

    onResetFields() {
        this.setState({
           someGlobalVariable: '',
        });
    }
}
const reqformdata = new YourForm

export default reqformdata

Save this to a folder called stores as yourForm.jsx.

Then you can do this in another page:

import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'

Reflux.defineReact(React)

class SomePage extends Reflux.Component {
    constructor(props) {
        super(props);
        this.state = {
            someLocalVariable: '',
        }
        this.stores = [
            YourForm,
        ]
    }
    render() {

        const myVar = this.state.someGlobalVariable;
        return (
            <Form>
                <div>{myVar}</div>
            </Form>
        )
    }
}
export default SomePage

If you had set this.state.someGlobalVariable in another component using a function like:

setSomeVariable(propertyTextToAdd) {
    this.setState({
       myGlobalVariable: propertyTextToAdd
   });
}

that you bind in the constructor with:

this.setSomeVariable = this.setSomeVariable.bind(this);

the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

I think this should work.

UPDATE QuestionTrackings
SET QuestionID = (SELECT QuestionID
                  FROM AnswerTrackings
                  WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
WHERE QuestionID IS NULL
AND AnswerID IS NOT NULL;

How to vertically center a "div" element for all browsers using CSS?

To vertical-align a box in web page, including Internet Explorer 6, you may use:

  1. Conditional comments
  2. The haslayout property
  3. display: table-value for others (and now flex)

Fiddle

_x000D_
_x000D_
/* Internet Explorer 8 and others */_x000D_
.main {_x000D_
  width: 500px;_x000D_
  margin: auto;_x000D_
  border: solid;_x000D_
}_x000D_
html {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
body {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<!-- [if lte IE 7]>_x000D_
<style> /* Should be in the <head> */_x000D_
    html, body , .ie {_x000D_
        height: 100%;_x000D_
        text-align: center;_x000D_
        white-space: nowrap;_x000D_
    }_x000D_
    .ie , .main{_x000D_
        display: inline; /* Used with zoom in case you take a block element instead an inline element */_x000D_
        zoom: 1;_x000D_
        vertical-align: middle;_x000D_
        text-align: left;_x000D_
        white-space: normal;_x000D_
    }_x000D_
</style>_x000D_
<b class="ie"></b>_x000D_
<!--[endif]-->_x000D_
<div class="main">_x000D_
  <p>Fill it up with your content </p>_x000D_
  <p><a href="https://jsfiddle.net/h8z24s5v/embedded/result/">JsFiddle versie</a></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Actually, Internet Explorer 7 would bring some trouble here being the only which will strictly apply height: 100% on HTML/body elements.


But, this is past and today and who still minds old versions of Internet Explorer, table/table-cell is just fine, display: flex is promising, and display: grid will show up some day.


Another nowdays example via flex

_x000D_
_x000D_
html {_x000D_
  display: flex;_x000D_
  min-height: 100vh;/* or height */_x000D_
}_x000D_
_x000D_
body {_x000D_
  margin: auto;_x000D_
}
_x000D_
<div>Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

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

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

Creating a textarea with auto-resize

Just use <pre> </pre> with some styles like:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }

Kill some processes by .exe file name

You can use Process.GetProcesses() to get the currently running processes, then Process.Kill() to kill a process.

What is the difference between concurrency and parallelism?

Explanation from this source was helpful for me:

Concurrency is related to how an application handles multiple tasks it works on. An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently).

Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel.

As you can see, an application can be concurrent, but not parallel. This means that it processes more than one task at the same time, but the tasks are not broken down into subtasks.

An application can also be parallel but not concurrent. This means that the application only works on one task at a time, and this task is broken down into subtasks which can be processed in parallel.

Additionally, an application can be neither concurrent nor parallel. This means that it works on only one task at a time, and the task is never broken down into subtasks for parallel execution.

Finally, an application can also be both concurrent and parallel, in that it both works on multiple tasks at the same time, and also breaks each task down into subtasks for parallel execution. However, some of the benefits of concurrency and parallelism may be lost in this scenario, as the CPUs in the computer are already kept reasonably busy with either concurrency or parallelism alone. Combining it may lead to only a small performance gain or even performance loss.

Getting the Facebook like/share count for a given URL

You Can Show Facebook Share/Like Count Like This: ( Tested and Verified)

$url = http://www.yourdomainname.com // You can use inner pages

$rest_url = "http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls=".urlencode($url);

$json = json_decode(file_get_contents($rest_url),true);


echo Facebook Shares = '.$json[0][share_count];

echo Facebook Likes = '.$json[0][like_count];

echo Facebook Comments = '.$json[0][comment_count];

NuGet Package Restore Not Working

I have run into this problem in two scenarios.

First, when I attempt to build my solution from the command line using msbuild.exe. Secondly, when I attempt to build the sln and the containing projects on my build server using TFS and CI.

I get errors claiming that references are missing. When inspecting both my local build directory and the TFS server's I see that the /packages folder is not created, and the nuget packages are not copied over. Following the instructions listed in Alexandre's answer http://nuget.codeplex.com/workitem/1879 also did not work for me.

I've enabled Restore Packages via VS2010 and I have seen builds only work from within VS2010. Again, using msbuild fails.My workaround is probably totally invalid, but for my environment this got everything working from a command line build locally, as well as from a CI build in TFS.

I went into .\nuget and changed this line in the .nuget\NuGet.targets file:

from:

<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" -o "$(PackagesDir)"</RestoreCommand>

to: (notice, without the quotes around the variables)

<RestoreCommand>$(NuGetCommand) install $(PackagesConfig) -source $(PackageSources) -o $(PackagesDir)</RestoreCommand>

I understand that if my directories have spaces in them, this will fail, but I don't have spaces in my directories and so this workaround got my builds to complete successfully...for the time being.

I will say that turning on diagnostic level logging in your build will help show what commands are being executed by msbuild. This is what led me to hacking the targets file temporarily.

Max length UITextField

You need to check whether the existing string plus the input is greater than 10.

   func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,    replacementString string: String!) -> Bool {
      NSUInteger newLength = textField.text.length + string.length - range.length;
      return !(newLength > 10)
   }