Programs & Examples On #Farseer

C#/XNA port of the Box2D physics engine.

How to display loading message when an iFrame is loading?

You can use below code .

 iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}

Peak detection in a 2D array

I'm sure you have enough to go on by now, but I can't help but suggest using the k-means clustering method. k-means is an unsupervised clustering algorithm which will take you data (in any number of dimensions - I happen to do this in 3D) and arrange it into k clusters with distinct boundaries. It's nice here because you know exactly how many toes these canines (should) have.

Additionally, it's implemented in Scipy which is really nice (

Here's an example of what it can do to spatially resolve 3D clusters: enter image description here

What you want to do is a bit different (2D and includes pressure values), but I still think you could give it a shot.

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

How to post JSON to a server using C#?

WARNING! I have a very strong view on this subject.

.NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

There is not much between them, but I would give ServiceStack.Text the slight edge …

  • Github stars are roughly the same.
  • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
  • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

var response = ""
    .PostJsonToUrl(new Login { Username="admin", Password="mypassword" });

That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

jQuery Ajax requests are getting cancelled without being sent

I had the same problem, but in my case it turned out to be a cookie issue. The guys working on the back-end had changed the path of the JSESSIONID cookie that's set when we log in to our app, and I had an old cookie by that name on my computer, but with the old path. So when I tried logging in the browser (Chrome) sent two cookies called JSESSIONID, with different values, to the server - which understandably confused it - so it cancelled the request. Deleting the cookies from my computer fixed it.

How to edit HTML input value colour?

You can add color in the style rule of your input: color:#ccc;

Warning: push.default is unset; its implicit value is changing in Git 2.0

Brought my answer over from other thread that may close as a duplicate...

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

How do I empty an input value with jQuery?

To make values empty you can do the following:


To get the selected value you can do:

var value = $("#element").val();

Where #element is the id of the element you wish to select.

Append a tuple to a list - what's the difference between two ways?

There should be no difference, but your tuple method is wrong, try:

a_list.append(tuple([3, 4]))

Change bullets color of an HTML list without using span

Inline version, works for Outlook Desktop:

<ul style="list-style:square;">
  <li style="color:red;"><span style="color:black;">Lorem.</span></li>
  <li style="color:red;"><span style="color:black;">Lorem.</span></li>


CSS Selector for <input type="?"

Sadly the other posters are correct that you're ...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.

Out of completeness, the type selector is - similar to xpath - of the form [attribute=value] but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.

JQuery Calculate Day Difference in 2 date textboxes

Number of days calculation between two dates.

    $(document).ready(function () {
        $('.submit').on('click', function () {
            var startDate = $('.start-date').val();
            var endDate = $('.end-date').val();

            var start = new Date(startDate);
            var end = new Date(endDate);

            var diffDate = (end - start) / (1000 * 60 * 60 * 24);
            var days = Math.round(diffDate);

How to Round to the nearest whole number in C#

Use Math.Round:

double roundedValue = Math.Round(value, 0)

How can I remove all my changes in my SVN working directory?

svn status | grep '^M' | sed -e 's/^.//' | xargs rm

svn update

Will remove any file which has been modified. I seem to remember having trouble with revert when files and directories may have been added.

Get image data url in JavaScript?

This Function takes the URL then returns the image BASE64

function getBase64FromImageUrl(url) {
    var img = new Image();

    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width =this.width;
        canvas.height =this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));

    img.src = url;

Call it like this : getBase64FromImageUrl("images/slbltxt.png")

How to prevent Right Click option using jquery

<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false" >

Set these attributes in your selected tag

See here Working Example -

No Need JQuery (like)

How to add Button over image using CSS?

If I understood correctly, I would change the HTML to something like this:

<div id="shop">
    <div class="content">
        <img src=""/> 
        <a href="#">Counter-Strike 1.6 Steam</a>

Then I would be able to use position:absolute and position:relative to force the blue button down.

I have created a jsfiddle:

How do I set an ASP.NET Label text from code behind on page load?

If you are just placing the code on the page, usually the code behind will get an auto generated field you to use like @Oded has shown.

In other cases, you can always use this code:

Label myLabel = this.FindControl("myLabel") as Label; // this is your Page class

if(myLabel != null)
   myLabel.Text = "SomeText";

How to add a class to a given element?

When the work I'm doing doesn't warrant using a library, I use these two functions:

function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
    //add a space if the element already has class
    if( cn != '' ) {
        classname = ' '+classname;
    element.className = cn+classname;

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

This is a fix for people who are not using maven. You also need to add standard.jar to your lib folder for the core tag library to work. Works for jstl version 1.1.

<%@taglib prefix="core" uri=""%>

Razor View Engine : An expression tree may not contain a dynamic operation

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

Simplest way to throw an error/exception with a custom message in Swift 2?

Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError that implements the LocalizedError protocol.

struct DisplayableError: Error, LocalizedError {
    let errorDescription: String?

    init(_ description: String) {
        errorDescription = description

Usage for throwing:

throw DisplayableError("Out of pixie dust.")

Usage for display:

let messageToDisplay = error.localizedDescription

How can I access the MySQL command line with XAMPP for Windows?

For windows

mysql -u root -p

Just a simple commands for linux to open mysql :

sudo /opt/lampp/bin/mysql

Disable arrow key scrolling in users browser

I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

window.addEventListener('keydown', (e) => {
    if ( != 'input') {   // if you need to filter <input> elements
        switch (e.keyCode) {
            case 37: // left
            case 39: // right
            case 38: // up
            case 40: // down
}, {
    capture: true,   // this disables arrow key scrolling in modern Chrome
    passive: false   // this is optional, my code works without it

Quote for EventTarget.addEventListener() from MDN

options Optional
   An options object specifies characteristics about the event listener. The available options are:

   A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
   A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
    return retval;

var retval = getMachine(color, qty);

char initial value in Java

you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.

How do I exit the Vim editor?

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.

I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
>>> u'ñ'.encode('utf8')
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

Class Not Found: Empty Test Suite in IntelliJ

I had the same question when I import some jar from Maven, and subsequently, cause the empty-test-suite error.

In my case, it was because the maven resetting the module files. Which I resolved by clearing my default configuration:

  1. Open Project structure with shift-ctrl-alt-s shortcut

Screenshot of PModules Sources

  1. Look at the Modules > Sources and fill the Sources package or test Package.

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

You can use the GraphRequest class to issue calls to the Facebook Graph API to get user information. See for more info.

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;


Scanner in = new Scanner(;
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Logging POST data from $request_body

FWIW, this config worked for me:

location = /logpush.html {
  if ($request_method = POST) {
    access_log /var/log/nginx/push.log push_requests;
    proxy_pass $scheme://;
  return 200 $scheme://$host/serviceup.html;
location /logsink {
  return 200;

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)


Matplotlib make tick labels font size smaller

You can also change label display parameters like fontsize with a line like this:

zed = [tick.label.set_fontsize(14) for tick in ax.yaxis.get_major_ticks()]

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

I found a free plugin that can generate class diagrams with android studio. It's called SimpleUML.

Update Android Studio 2.2+: To install the plugin, follow steps in this answer:

Older version of Android Studio On Mac: go to Android Studio -> Preferences -> Plugins

On Windows: go to Android Studio -> File -> Settings -> Plugins

Click on Browse repositories... and search for SimpleUMLCE (CE means Community Edition, this is what android studio is based on).

Install it, restart, then you can do a right click on the folder containing the classes you want to visualize, and select Add to simpleUML Diagram.

That's it; you have you fancy class diagram generated from your code!

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Trigger change event of dropdown

Try this:


Works for me.

On one line together with setting the value: $('#id').val(16).change();

How to format a date using ng-model?

Use custom validation of forms Demo:

Directive using formaters and parsers and MomentJS )

angModule.directive('moDateInput', function ($window) {
    return {
        link:function (scope, elm, attrs, ctrl) {
            var moment = $window.moment;
            var dateFormat = attrs.moDateInput;
            attrs.$observe('moDateInput', function (newValue) {
                if (dateFormat == newValue || !ctrl.$modelValue) return;
                dateFormat = newValue;
                ctrl.$modelValue = new Date(ctrl.$setViewValue);

            ctrl.$formatters.unshift(function (modelValue) {
                if (!dateFormat || !modelValue) return "";
                var retVal = moment(modelValue).format(dateFormat);
                return retVal;

            ctrl.$parsers.unshift(function (viewValue) {
                var date = moment(viewValue, dateFormat);
                return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";

Regarding Java switch statements - using return and omitting breaks in each case

I suggest you not use literals.

Other than that the style itself looks fine.

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  // Templating
  'GString template' {
  // I find this more readable
  'Readable GString template' {
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )

That gives me the following output on my machine:

* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
  'Readable GString template toString' {

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  // Templating
  'GString template' {
  // I find this more readable
  'Readable GString template' {
  'GString template toString' {
  'Readable GString template toString' {
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )


* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

Add Expires headers

try this solution and it is working fine for me

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 


How do I add a library path in cmake?

You had better use find_library command instead of link_directories. Concretely speaking there are two ways:

  1. designate the path within the command

    find_library(NAMES gtest PATHS path1 path2 ... pathN)

  2. set the variable CMAKE_LIBRARY_PATH

    set(CMAKE_LIBRARY_PATH path1 path2)
    find_library(NAMES gtest)

the reason is as flowings:

Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).

Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).

If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.

How to sum all column values in multi-dimensional array?

Go through each item of the array and sum values to previous values if they exist, if not just assign the value.

$array = 

$result = array_reduce($array, function($carry, $item) {
    foreach($item as $k => $v)
        $carry[$k] = $v + ($carry[$k] ?? 0);

    return $carry;
}, []);



    [a] => 6
    [b] => 3
    [c] => 1
    [d] => 3

Or just loop through each sub array, and group the values for each column. Eventually summing them:

foreach($array as $subarray)
    foreach($subarray as $key => $value)
        $grouped[$key][] = $value;

$sums = array_map('array_sum', $grouped);

Datatable select with multiple conditions

Try this,
I think ,this is one of the simple solutions.

int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);

Make sure,combination of values for column A, B and C is unique in the datatable.

How do I remove javascript validation from my eclipse project?

Turn off the JavaScript Validator in the "Builders" config for your project:

  1. Right click your project
  2. Select Properties -> Builders
  3. Uncheck the "JavaScript Validator"

Then either restart your Eclipse or/and rename the .js to something like .js_ then back again.

Head and tail in one line

For O(1) complexity of head,tail operation you should use deque however.

Following way:

from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l

It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.

How large is a DWORD with 32- and 64-bit code?

Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.

In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.

You can find the official list here:

All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:


and restart the server. Change the password, and set the value back to 0, and restart again.

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

How to Implement Custom Table View Section Headers and Footers with Storyboard

If you need a Swift Implementation of this follow the directions on the accepted answer and then in you UITableViewController implement the following methods:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return tableView.dequeueReusableCell(withIdentifier: "CustomHeader")

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 75

Setting Icon for wpf application (VS 08)

After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:

  1. Put the icon in a folder <icon_path> in the project directory
  2. Mimic the folder path <icon_path> in the solution
  3. Add a new item (your icon) in the solution folder you created
  4. Add the following code in the WPF window's code behind:

Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));

Please inform me if you have any difficulties implementing this solution so I can help.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;

Add this class to your iframe and you're done:

<iframe src="" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How can I declare a two dimensional string array?

You just declared a jagged array. Such kind of arrays can have different sizes for all dimensions. For example:

string[][] jaggedStrings =  {
new string[] {"x","y","z"},
new string[] {"x","y"},
new string[] {"x"}

In your case you need regular array. See answers above. More about jagged arrays

Getting Image from URL (Java)


public class ImageComponent extends JComponent {
  private final BufferedImage img;

  public ImageComponent(URL url) throws IOException {
    img =;
    setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));


  protected void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);

  public static void main(String[] args) throws Exception {
    final URL kitten = new URL("");

    final ImageComponent image = new ImageComponent(kitten);

    JFrame frame = new JFrame("Test");
    frame.add(new JScrollPane(image));

    frame.setSize(400, 300);

CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

Remove all items from a FormArray in Angular

Use FormArray.clear() to remove all the elements of an array in a FormArray

Best way to create an empty map in Java

Either Collections.emptyMap(), or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {


    public Sorting(String property, String direction) { = property;
        this.direction = direction;

    public String getProperty() {
        return property;

    public void setProperty(String property) { = property;

    public String getDirection() {
        return direction;

    public void setDirection(String direction) {
        this.direction = direction;

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));

How to assign Php variable value to Javascript variable?

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

How to search in a List of Java object

I modifie this list and add a List to the samples try this


Sample {
   List<String> values;
   List<String> getList() {
   return values}

for(Sample s : list) {
   if(s.getString.getList.contains("three") {
      return s;

Get a filtered list of files in a directory

Another option:

>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')

How to get HttpClient returning status code and response body?

Fluent facade API:

Response response = Request.Get(uri)
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // ??????????(???????)
    String responseContent = EntityUtils.toString(

Is there possibility of sum of ArrayList without looping

This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..


public static void main(String args []){
    List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));    


See StatUtils api

Aren't promises just callbacks?

Yes, Promises are asynchronous callbacks. They can't do anything that callbacks can't do, and you face the same problems with asynchrony as with plain callbacks.

However, Promises are more than just callbacks. They are a very mighty abstraction, allow cleaner and better, functional code with less error-prone boilerplate.

So what's the main idea?

Promises are objects representing the result of a single (asynchronous) computation. They resolve to that result only once. There's a few things what this means:

Promises implement an observer pattern:

  • You don't need to know the callbacks that will use the value before the task completes.
  • Instead of expecting callbacks as arguments to your functions, you can easily return a Promise object
  • The promise will store the value, and you can transparently add a callback whenever you want. It will be called when the result is available. "Transparency" implies that when you have a promise and add a callback to it, it doesn't make a difference to your code whether the result has arrived yet - the API and contracts are the same, simplifying caching/memoisation a lot.
  • You can add multiple callbacks easily

Promises are chainable (monadic, if you want):

  • If you need to transform the value that a promise represents, you map a transform function over the promise and get back a new promise that represents the transformed result. You cannot synchronously get the value to use it somehow, but you can easily lift the transformation in the promise context. No boilerplate callbacks.
  • If you want to chain two asynchronous tasks, you can use the .then() method. It will take a callback to be called with the first result, and returns a promise for the result of the promise that the callback returns.

Sounds complicated? Time for a code example.

var p1 = api1(); // returning a promise
var p3 = p1.then(function(api1Result) {
    var p2 = api2(); // returning a promise
    return p2; // The result of p2 …
}); // … becomes the result of p3

// So it does not make a difference whether you write
api1().then(function(api1Result) {
    return api2().then(console.log)
// or the flattened version
api1().then(function(api1Result) {
    return api2();

Flattening does not come magically, but you can easily do it. For your heavily nested example, the (near) equivalent would be

api1().then(api2).then(api3).then(/* do-work-callback */);

If seeing the code of these methods helps understanding, here's a most basic promise lib in a few lines.

What's the big fuss about promises?

The Promise abstraction allows much better composability of functions. For example, next to then for chaining, the all function creates a promise for the combined result of multiple parallel-waiting promises.

Last but not least Promises come with integrated error handling. The result of the computation might be that either the promise is fulfilled with a value, or it is rejected with a reason. All the composition functions handle this automatically and propagate errors in promise chains, so that you don't need to care about it explicitly everywhere - in contrast to a plain-callback implementation. In the end, you can add a dedicated error callback for all occurred exceptions.

Not to mention having to convert things to promises.

That's quite trivial actually with good promise libraries, see How do I convert an existing callback API to promises?

URL to load resources from the classpath in Java

Intro and basic Implementation

First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called Handler; this allows you to specify java and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").


new URL("classpath:org/my/package/resource.extension").openConnection();




/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public Handler() {
        this.classLoader = getClass().getClassLoader();

    public Handler(ClassLoader classLoader) {
        this.classLoader = classLoader;

    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();

Launch issues

If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why I need all this).


Manual code Handler specification

If you control the code, you can do

new URL(null, "classpath:some/package/resource.extension", new

and this will use your handler to open the connection.

But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...

JVM Handler registration

The ultimate option is to register a URLStreamHandlerFactory that will handle all urls across the jvm:


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

class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
    private final Map<String, URLStreamHandler> protocolHandlers;

    public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers = new HashMap<String, URLStreamHandler>();
        addHandler(protocol, urlHandler);

    public void addHandler(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers.put(protocol, urlHandler);

    public URLStreamHandler createURLStreamHandler(String protocol) {
        return protocolHandlers.get(protocol);

To register the handler, call URL.setURLStreamHandlerFactory() with your configured factory. Then do new URL("classpath:org/my/package/resource.extension") like the first example and away you go.

JVM Handler Registration Issue

Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!


I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a URLStreamHandlerFactory that uses ThreadLocals to store URLStreamHandlers for each Thread.currentThread().getContextClassLoader(). I'll even give you my modifications and test classes. localhost/ - Connection refused

You just have to use your local IP address:using the cmd command "ipconfig" and your server port number like this:

String webServiceUrl = "http://192.168.X.X:your_local_server_port/your_web_service_name.php"

And make sure you did set the internet permission in your project manifest

It's working perfectly for me

Good Luck

customize Android Facebook Login button

In order to have completely custom facebook login button without using com.facebook.widget.LoginButton.

According to facebook sdk 4.x,

There new concept of login as from facebook

LoginManager and AccessToken - These new classes perform Facebook Login

So, Now you can access Facebook authentication without Facebook login button as



    public void onCreate(Bundle savedInstanceState) {


        callbackManager = CallbackManager.Factory.create();

                new FacebookCallback<LoginResult>() {
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("Success", "Login");


                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();

                    public void onError(FacebookException exception) {
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();


        Button btn_fb_login = (Button)findViewById(;

        btn_fb_login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                  LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data); 

How to temporarily exit Vim and go back

If you don't mind using your mouse a little bit:

  • Start your terminal,
  • select a file,
  • select Open Tab.

This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell and exit).

How to run iPhone emulator WITHOUT starting Xcode?

From Terminal you have to run:

open -a Simulator

Field 'id' doesn't have a default value?

This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.

There are a couple of fixes for this.

First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:

ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;

However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.

If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:


Save the file and restart Mysql.


How to add image background to btn-default twitter-bootstrap button?

This works with font awesome:

<button class="btn btn-outline-success">
   <i class="fa fa-print" aria-hidden="true"></i>

How do I clear all options in a dropdown box?

Using JQuery is a prettier, shorter & smarter way to do it!


Android read text raw resource file

InputStream is=getResources().openRawResource(;
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();

Launch Failed. Binary not found. CDT on Eclipse Helios

make sure you have GDB installed on your system...

If your using Linux based OS simply in a terminal type:

sudo apt-get install gdt 

when finished downloading extract the file and install.

close your IDE (in this case eclipse and open it again and run your project.

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)

If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/ to the end of the repository URL and to generate a zipfile of the master branch.


to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

How to do a num_rows() on COUNT query in codeigniter?

As per CI Docs we can use the following,

$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();

If we want to get total rows in the table without any condition, simple use

echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table

Rename a file using Java

Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {

Display UIViewController as Popup in iPhone

Feel free to use my form sheet controller MZFormSheetControllerfor iPhone, in example project there are many examples on how to present modal view controller which will not cover full window and has many presentation/transition styles.

You can also try newest version of MZFormSheetController which is called MZFormSheetPresentationController and have a lot of more features.

subquery in codeigniter active record

I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

$subquery = 'SELECT id_cer FROM revokace';

$this->db->where_not_in(id, $subquery);
$query = $this->db->get();

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy


    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )


I have a java.util.Date in the format yyyy-mm-dd

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.


The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );


If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();


If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

About java.time

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

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to create jar file with package structure?

Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.

Go directory bin using command:

cd C:/workspace/MyProj/bin

Step 2: Use below command to generate jar file.

jar cvf helloworld.jar com\test\hello\Hello.class  com\test\orld\HelloWorld.class

Using the above command the classes will be placed in a jar in a directory structure.

How do you launch the JavaScript debugger in Google Chrome?

From the console in Chrome, you can do console.log(data_to_be_displayed).

Set value for particular cell in pandas DataFrame with iloc

Another way is to get the row index and then use df.loc or

# get row index 'label' from row number 'irow'
label = df.index.values[irow][label, 'COL_NAME'] = x

Python pip install fails: invalid command egg_info

I just convert liquidki's answer into Ubuntu commands. On an Ubuntu based system it works!:

sudo apt -y install python-pip
pip install -U pip
sudo pip install -U setuptools

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

How to view Plugin Manager in Notepad++

  1. You can download the latest Plugin Manager version

  2. Unzip the file.

  3. Copy\updater\gpup.exe



  1. Copy\plugins\PluginManager.dll



  1. Start or restart Notepad++.
  2. Enjoy!

add title attribute from css

Quentin is correct, it can't be done with CSS. If you want to add a title attribute, you can do it with JavaScript. Here's an example using jQuery:


How can I install Visual Studio Code extensions offline?

If you have a specific (legacy) version of VSCode on your offline instance, pulling the latest extensions might not properly integrate.

To make sure that VSCode and the extensions work together, they must all be installed together on the online machine. This resolves any dependencies (with specific versions), and ensures the exact configuration of the offline instance.

Quick steps:

Install the VSCode version, turn off updating, and install the extensions. Copy the extensions from the installed location and place them on the target machine.

Detailed steps:

Install the exact version of VSCode on online machine. Then turn off updates by going to File -> Preferences -> Settings. In the Settings window, under User Settings -> Application, go to Update section, and change the parameter for Channel to none. This prevents VSCode from reaching out to the internet and auto-updating your versions to the latest.

Then go to the VSCode extensions section and install all of your desired extensions. Copy the installed extensions from their install location (with windows its C:\Users\<username>\.vscode\extensions) to the same location on the target machine.

Works perfectly.

Block Comments in a Shell Script

Another mode is: If your editor HAS NO BLOCK comment option,

  1. Open a second instance of the editor (for example File=>New File...)
  2. From THE PREVIOUS file you are working on, select ONLY THE PART YOU WANT COMMENT
  3. Copy and paste it in the window of the new temporary file...
  4. Open the Edit menu, select REPLACE and input as string to be replaced '\n'
  5. input as replace string: '\n#'
  6. press the button 'replace ALL'


it WORKS with ANY editor

Check whether a string contains a substring

Case Insensitive Substring Example

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";

rawQuery(query, selectionArgs)

if your SQL query is this

SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'

then rawQuery will be

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"} 
db.rawQuery(query, selectionArgs);

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

or set the HTTP_PROXY and HTTPS_PROXY environment variables. Note that in your case you need to add the scheme to the proxy url, like


Maven Installation OSX Error Unsupported major.minor version 51.0

A dynamic $HOME/.zshrc solution, if you're like me ie. Linux @ work; MBP/A @ home

if [[ $(uname) == "Darwin" ]]; then export OSX=1; fi
if [[ $(uname) ==  "Linux" ]]; then export LINUX=1; fi

if [[ -n $OSX ]]; then
        export JAVA_HOME=$(/usr/libexec/java_home)
        export JAVA_HOME=/usr/lib/jvm/default-java

What is the standard Python docstring format?

It's Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It's the de-facto standard for documenting Python projects. The product is beautiful - take a look at . The website Read the Docs will host your docs for free.

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

Is "else if" faster than "switch() case"?

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

conversion from string to json object android

Using Kotlin

    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
      val jsonObject = JSONObject(data)
      val infoObj = jsonObject.getJSONObject("ApiInfo")
    } catch (e: Exception) {

Division in Python 2.7. and 3.3

In Python 3, / is float division

In Python 2, / is integer division (assuming int inputs)

In both 2 and 3, // is integer division

(To get float division in Python 2 requires either of the operands be a float, either as 20. or float(20))

Force SSL/https using .htaccess and mod_rewrite

I found a mod_rewrite solution that works well for both proxied and unproxied servers.

If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.


  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.


  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.


  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning


  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

Open a facebook link by native Facebook app on iOS

If the Facebook application is logged in, the page will be opened when executing the following code. If the Facebook application is not logged in when executing the code, the user will then be redirected to the Facebook app to login and then after connecting the Facebook is not redirected to the page!

NSURL *fbNativeAppURL = [NSURL URLWithString:@"fb://page/yourPageIDHere"] [[UIApplication sharedApplication] openURL:fbNativeAppURL]

How do I rename a repository on GitHub?

I see a lot of positive feedback to responses I don't find accurate/complete at all.

There are two things to have in mind:

  • Remote repository
  • Local copy of the repository

If you haven't cloned your repo in your machine yet, you just need to rename the Github repository and then proceed to clone the repo so you can have a local copy. In order to rename the Github repo, you just need to:

  1. Go to the repository site (i.e
  2. In the navigation bar, you will see a tab named "Settings". Click on it.
  3. Just edit the current repository name with the desired one and press "Rename".
  4. Clone the repository as usual (i.e git clone

If you already have a local copy of the project, apart from following the steps above, you need to make sure your local repository (root folder) is renamed properly and it's pointing to the right remote url :) link. In order to achieve that, do the following:

  1. You might want to use the new given name for your repo. To do so, rename the local folder either by using the OS GUI(Finder, Windows Explorer, etc.) or console:

mv -R current-repo-name new-repo-name

  1. Change the remote url. From the root of the folder, use the following:

$ git remote set-url origin


$ git remote set-url origin [email protected]:userX/repositoryU.git

The second step is not mandatory, though. Github announced a while ago that they would redirect all requests from previous repository urls to the assigned ones. That means you don't need to use $ git remote set-url ..., but they still encourage you to do so to avoid confusion.

Hope it helped. If you have any questions or the post is not clear enough, let me know.

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(;
int x = 10;

Styling Google Maps InfoWindow

I have design google map infowindow with image & some content as per below.

enter image description here

map_script (Just for infowindow html reference)

for (i = 0; i < locations.length; i++) { 
    var latlng = new google.maps.LatLng(locations[i][1], locations[i][2]);
    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: "<?php echo plugins_url( 'assets/img/map-pin.png', ELEMENTOR_ES__FILE__ ); ?>"

    var property_img = locations[i][6],
    title = locations[i][0],
    price = locations[i][3],
    bedrooms = locations[i][4],
    type = locations[i][5],
    listed_on = locations[i][7],
    prop_url = locations[i][8];

    content = "<div class='map_info_wrapper'><a href="+prop_url+"><div class='img_wrapper'><img src="+property_img+"></div>"+
    "<div class='property_content_wrap'>"+
    "<div class='property_title'>"+

    "<div class='property_price'>"+

    "<div class='property_bed_type'>"+

    "<div class='property_listed_date'>"+
    "<span>Listed on "+listed_on+"</span>"+

    google.maps.event.addListener(marker, 'click', (function(marker, content, i) {
        return function() {
  , marker);
    })(marker, content, i));

Most important thing is CSS

 #propertymap .gm-style-iw{
    font-family: "Georgia", "Open Sans", Sans-serif;
    text-align: center;
    width: 100% !important;
    border-radius: 0;
    left: 0 !important;
    top: 20px !important;

 #propertymap .gm-style > div > div > div > div > div > div > div {
    background: none!important;

.gm-style > div > div > div > div > div > div > div:nth-child(2) {
     box-shadow: none!important;
 #propertymap .gm-style-iw > div > div{
    background: #FFF!important;

 #propertymap .gm-style-iw a{
    text-decoration: none;

 #propertymap .gm-style-iw > div{
    width: 245px !important

 #propertymap .gm-style-iw .img_wrapper {
    height: 150px;  
    overflow: hidden;
    width: 100%;
    text-align: center;
    margin: 0px auto;

 #propertymap .gm-style-iw .img_wrapper > img {
    width: 100%;

 #propertymap .gm-style-iw .property_content_wrap {
    padding: 0px 20px;

 #propertymap .gm-style-iw .property_title{
    min-height: auto;

Select all DIV text with single mouse click

UPDATE 2017:

To select the node's contents call:


This works on all modern browsers including IE9+ (in standards mode).

Runnable Example:

function select(id) {_x000D_
      document.getElementById("target-div") _x000D_
#outer-div  { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button      { margin: 1rem; }
<div id="outer-div">_x000D_
  <div id="target-div">_x000D_
    Some content for the _x000D_
    <br>Target DIV_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>

The original answer below is obsolete since window.getSelection().addRange(range); has been deprecated

Original Answer:

All of the examples above use:

    var range = document.createRange();
    range.selectNode( ... );

but the problem with that is that it selects the Node itself including the DIV tag etc.

To select the Node's text as per the OP question you need to call instead:

    range.selectNodeContents( ... )

So the full snippet would be:

    function selectText( containerid ) {

        var node = document.getElementById( containerid );

        if ( document.selection ) {
            var range = document.body.createTextRange();
            range.moveToElementText( node  );
        } else if ( window.getSelection ) {
            var range = document.createRange();
            range.selectNodeContents( node );
            window.getSelection().addRange( range );

Image UriSource and Data Binding

You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

And the class property is simply this

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            return DependencyProperty.UnsetValue;

        return image;

I suppose it may be a little more work than the value converter, but it is another option.

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

How to Check whether Session is Expired or not in


You can use the IsNewSession property to check if the session was created on the request of the page

protected void Page_Load() 
   if (Context.Session != null) 
      if (Session.IsNewSession) 
         string cookieHeader = Request.Headers["Cookie"]; 
         if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) 


Store Userid in session variable when user logs into website and check on your master page or created base page form which other page gets inherits. Then in page load check that Userid is present and not if not then redirect to login page.

  //session expire redirect to login page 

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:


breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

CSS: Position text in the middle of the page

Here's a method using display:flex:

.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_

View on Codepen
Check Browser Compatability

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

Using the passwd command from within a shell script

Here-document works if your passwd doesn't support --stdin and you don't want to (or can't) use chpasswd for some reason.


#!/usr/bin/env bash


passwd ${username} << EOD

Tested under Arch Linux. This passwd is an element of shadow-utils and installed from the core/filesystem package, which you usually have by default since the package is required by core/base.

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:


Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

If Python is interpreted, what are .pyc files?

Python's *.py file is just a text file in which you write some lines of code. When you try to execute this file using say "python"

This command invokes Python Virtual Machine. Python Virtual Machine has 2 components: "compiler" and "interpreter". Interpreter cannot directly read the text in *.py file, so this text is first converted into a byte code which is targeted to the PVM (not hardware but PVM). PVM executes this byte code. *.pyc file is also generated, as part of running it which performs your import operation on file in shell or in some other file.

If this *.pyc file is already generated then every next time you run/execute your *.py file, system directly loads your *.pyc file which won't need any compilation(This will save you some machine cycles of processor).

Once the *.pyc file is generated, there is no need of *.py file, unless you edit it.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

An asynchronous version of extension function:

    public static async Task<WebResponse> GetResponseAsyncNoEx(this WebRequest request)
            return await request.GetResponseAsync();
        catch(WebException ex)
            return ex.Response;

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

Following @GregaKešpret you can make an infix operator:

`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x

Selecting a row in DataGridView programmatically

Try This:


What is the difference between join and merge in Pandas?

I always use join on indices:

import pandas as pd
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]}).set_index('key')
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]}).set_index('key')
left.join(right, lsuffix='_l', rsuffix='_r')

     val_l  val_r
foo      1      4
bar      2      5

The same functionality can be had by using merge on the columns follows:

left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]})
left.merge(right, on=('key'), suffixes=('_l', '_r'))

   key  val_l  val_r
0  foo      1      4
1  bar      2      5

What's the safest way to iterate through the keys of a Perl hash?

I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious "they return different things" answer. In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.

All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself. I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it. I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)

Making view resize to its parent when added with addSubview

that's all you need

childView.frame = parentView.bounds

Android update activity UI from service

for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :

 IntentFilter filter = new IntentFilter();


 updateUIReciver = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                //UI update here


And from the service you send the intent like this:

Intent local = new Intent();



don't forget to unregister the recover in the activity on destroy :


What is the best way to compare 2 folder trees on windows?

If you can use a GUI tool, the best I tried is WinMerge - open source.

If not, then diff is your friend.

How to check db2 version

In z/OS while on version 10, use of CURRENT APPLICATION COMPATIBILITY is not allowed. You will have to resort to:


Here is a link to all the variables available:

How to get the unix timestamp in C#

As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds.

This is an instance method, so you are expected to call it on an instance of DateTimeOffset. You can also cast any instance of DateTime, though beware the timezone. To get the current timestamp:


To get the timestamp from a DateTime:

DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L | bash

How to get year and month from a date - PHP

I personally prefer using this shortcut. The output will still be the same, but you don't need to store the month and year in separate variables

$dateValue = '2012-01-05';
$formattedValue = date("F Y", strtotime($dateValue));
echo $formattedValue; //Output should be January 2012

A little side note on using this trick, you can use comma's to separate the month and year like so:

$formattedValue = date("F, Y", strtotime($dateValue));
echo $formattedValue //Output should be January, 2012

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

    var form = $(this).parents('form:first');

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission

To select fields inside the form, use the form context. For example:


Converting JSON data to Java object

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

package com.stackoverflow.q1688099;

import java.util.List;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.


class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }
    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

See also:

error opening trace file: No such file or directory (2)

I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.

What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).

screenshot of the AVD creation screen

Additional information:

while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:

"/Applications/Android" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none

WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img

I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

How to do this using jQuery - document.getElementById("selectlist").value

Chaos is spot on, though for these sorts of questions you should check out the Jquery Documentation online - it really is quite comprehensive. The feature you are after is called 'jquery selectors'

Generally you do $('#ID').val() - the .afterwards can do a number of things on the element that is returned from the selector. You can also select all of the elements on a certain class and do something to each of them. Check out the documentation for some good examples.

pretty-print JSON using JavaScript

If you need this to work in a textarea the accepted solution will not work.

<textarea id='textarea'></textarea>


function formatJSON(json,textarea) {
    var nl;
    if(textarea) {
        nl = "&#13;&#10;";
    } else {
        nl = "<br>";
    var tab = "&#160;&#160;&#160;&#160;";
    var ret = "";
    var numquotes = 0;
    var betweenquotes = false;
    var firstquote = false;
    for (var i = 0; i < json.length; i++) {
        var c = json[i];
        if(c == '"') {
            numquotes ++;
            if((numquotes + 2) % 2 == 1) {
                betweenquotes = true;
            } else {
                betweenquotes = false;
            if((numquotes + 3) % 4 == 0) {
                firstquote = true;
            } else {
                firstquote = false;

        if(c == '[' && !betweenquotes) {
            ret += c;
            ret += nl;
        if(c == '{' && !betweenquotes) {
            ret += tab;
            ret += c;
            ret += nl;
        if(c == '"' && firstquote) {
            ret += tab + tab;
            ret += c;
        } else if (c == '"' && !firstquote) {
            ret += c;
        if(c == ',' && !betweenquotes) {
            ret += c;
            ret += nl;
        if(c == '}' && !betweenquotes) {
            ret += nl;
            ret += tab;
            ret += c;
        if(c == ']' && !betweenquotes) {
            ret += nl;
            ret += c;
        ret += c;
    } // i loop
    return ret;

The specified child already has a parent. You must call removeView() on the child's parent first

if you are adding the same view repeatedly in a for loop .. if this is the case then try creating the View object of the layout inside the for loop . and add the view in side the for loop

To avoid such issues

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers

MySQL Query - Records between Today and Last 30 Days

You can also write this in mysql -

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);


Twitter Bootstrap onclick event on buttons-radio

If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2

Javascript code for the event:

$('#option1').parent().on("click", function () {
   alert("click fired"); 

WooCommerce: Finding the products in database

Bulk add new categories to Woo:

Insert category id, name, url key

INSERT INTO wp_terms 
  (57, 'Apples', 'fruit-apples', '0'),
  (58, 'Bananas', 'fruit-bananas', '0');

Set the term values as catergories

INSERT INTO wp_term_taxonomy 
  (57, 57, 'product_cat', '', 17, 0),
  (58, 58, 'product_cat', '', 17, 0)

17 - is parent category, if there is one

key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id

After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories

How to construct a WebSocket URI relative to the page URI?

Here is my version which adds the tcp port in case it's not 80 or 443:

function url(s) {
    var l = window.location;
    return ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + (((l.port != 80) && (l.port != 443)) ? ":" + l.port : "") + l.pathname + s;

Edit 1: Improved version as by suggestion of @kanaka :

function url(s) {
    var l = window.location;
    return ((l.protocol === "https:") ? "wss://" : "ws://") + + l.pathname + s;

Edit 2: Nowadays I create the WebSocket this:

var s = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + + "/ws");

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

Preferred method to store PHP arrays (json_encode vs serialize)

I made a small benchmark as well. My results were the same. But I need the decode performance. Where I noticed, like a few people above said as well, unserialize is faster than json_decode. unserialize takes roughly 60-70% of the json_decode time. So the conclusion is fairly simple: When you need performance in encoding, use json_encode, when you need performance when decoding, use unserialize. Because you can not merge the two functions you have to make a choise where you need more performance.

My benchmark in pseudo:

  • Define array $arr with a few random keys and values
  • for x < 100; x++; serialize and json_encode a array_rand of $arr
  • for y < 1000; y++; json_decode the json encoded string - calc time
  • for y < 1000; y++; unserialize the serialized string - calc time
  • echo the result which was faster

On avarage: unserialize won 96 times over 4 times the json_decode. With an avarage of roughly 1.5ms over 2.5ms.

JSON to PHP Array using file_get_contents

Check some typo ','

$jsonD = '{
                    "adate":"2 Hours ago",
                    "adesc":"test desc",
                    "adate":"20 Hours ago",
                    "adesc":"test desc1",
                    "adate":"1 Days ago",
                    "adesc":"test123 desc",
                    "adate":"2 Days ago",
                    "adesc":"test12345 desc",

$parseJ = json_decode($jsonD,true);


How to run a Runnable thread in Android at defined intervals?

I believe for this typical case, i.e. to run something with a fixed interval, Timer is more appropriate. Here is a simple example:

myTimer = new Timer();
myTimer.schedule(new TimerTask() {          
public void run() {
    // If you want to modify a view in your Activity
    MyActivity.this.runOnUiThread(new Runnable()
        public void run(){
            tv.append("Hello World");
}, 1000, 1000); // initial delay 1 second, interval 1 second

Using Timer has few advantages:

  • Initial delay and the interval can be easily specified in the schedule function arguments
  • The timer can be stopped by simply calling myTimer.cancel()
  • If you want to have only one thread running, remember to call myTimer.cancel() before scheduling a new one (if myTimer is not null)

API pagination best practices

I've thought long and hard about this and finally ended up with the solution I'll describe below. It's a pretty big step up in complexity but if you do make this step, you'll end up with what you are really after, which is deterministic results for future requests.

Your example of an item being deleted is only the tip of the iceberg. What if you are filtering by color=blue but someone changes item colors in between requests? Fetching all items in a paged manner reliably is impossible... unless... we implement revision history.

I've implemented it and it's actually less difficult than I expected. Here's what I did:

  • I created a single table changelogs with an auto-increment ID column
  • My entities have an id field, but this is not the primary key
  • The entities have a changeId field which is both the primary key as well as a foreign key to changelogs.
  • Whenever a user creates, updates or deletes a record, the system inserts a new record in changelogs, grabs the id and assigns it to a new version of the entity, which it then inserts in the DB
  • My queries select the maximum changeId (grouped by id) and self-join that to get the most recent versions of all records.
  • Filters are applied to the most recent records
  • A state field keeps track of whether an item is deleted
  • The max changeId is returned to the client and added as a query parameter in subsequent requests
  • Because only new changes are created, every single changeId represents a unique snapshot of the underlying data at the moment the change was created.
  • This means that you can cache the results of requests that have the parameter changeId in them forever. The results will never expire because they will never change.
  • This also opens up exciting feature such as rollback / revert, synching client cache etc. Any features that benefit from change history.

Ways to implement data versioning in MongoDB

Another option is to use mongoose-history plugin.

let mongoose = require('mongoose');
let mongooseHistory = require('mongoose-history');
let Schema = mongoose.Schema;

let MySchema = Post = new Schema({
    title: String,
    status: Boolean

// The plugin will automatically create a new collection with the schema name + "_history".
// In this case, collection with name "my_schema_history" will be created.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:


You are passing the first item of words, instead of the array.

Instead, pass the array to the function:


Problem solved!

Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

How to remove whitespace from a string in typescript?


The trim() method removes whitespace from both sides of a string.



You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");


var out = "hello world".replace(/\s/g, "");_x000D_

How do I add python3 kernel to jupyter (IPython)

I managed to install a Python3 kernel besides the Python2. Here is the way I did it:

The latest working link can be found here.

The actual code is:

! mkdir -p ~/.ipython/kernels/python3
%%file ~/.ipython/kernels/python3/kernel.json

 "display_name": "IPython (Python 3)", 
 "language": "python", 
 "argv": [
  "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
  "-f", "{connection_file}"
 "codemirror_mode": {
  "version": 2, 
  "name": "ipython"

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

Both are poles on two different axis:

  • strongly typed vs. weakly typed
  • statically typed vs. dynamically typed

Strongly typed means, a will not be automatically converted from one type to another. Weakly typed is the opposite: Perl can use a string like "123" in a numeric context, by automatically converting it into the int 123. A strongly typed language like python will not do this.

Statically typed means, the compiler figures out the type of each variable at compile time. Dynamically typed languages only figure out the types of variables at runtime.

How do I directly modify a Google Chrome Extension File? (.CRX)

(Already said) I found this out while making some Chrome themes (which are long gone now... :-P)

Chrome themes, extensions, etc. are just compressed files. Get 7-zip or WinRar to unzip it. Each extension/theme has a manifest.json file. Open the manifest.json file in notepad. Then, if you know the coding, modify the code. There will be some other files. If you look in the manifest file you might be able to figure out what the are for. Then, you can change everything...

Notepad++ - How can I replace blank lines

By the way, in Notepad++ there's built-in plugin that can handle this: TextFX -> TextFX Edit -> Delete Blank Lines (first press CTRL+A to select all).

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    var categories = $(this).attr('rel');


You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

Exception: Can't bind to 'ngFor' since it isn't a known native property

Just to cover one more case when I was getting the same error and the reason was using in instead of of in iterator

Wrong way let file in files

Correct way let file of files

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

gc() can help

saving data as .RData, closing, re-opening R, and loading the RData can help.

see my answer here: for more details

Alternative to a goto statement in Java

While some commenters and downvoters argue that this isn't goto, the generated bytecode from the below Java statements really suggests that these statements really do express goto semantics.

Specifically, the do {...} while(true); loop in the second example is optimised by Java compilers in order not to evaluate the loop condition.

Jumping forward

label: {
  // do stuff
  if (check) break label;
  // do more stuff

In bytecode:

2  iload_1 [check]
3  ifeq 6          // Jumping forward
6  ..

Jumping backward

label: do {
  // do stuff
  if (check) continue label;
  // do more stuff
  break label;
} while(true);

In bytecode:

 2  iload_1 [check]
 3  ifeq 9
 6  goto 2          // Jumping backward
 9  ..

Perl: Use s/ (replace) and return new string

require 5.013002; # or better:    use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";

See perl5132delta:

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.

my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'

Passing multiple variables to another page in url

Short answer:

This is what you are trying to do but it poses some security and encoding problems so don't do it.

$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;

Long answer:

All variables in querystrings need to be urlencoded to ensure proper transmission. You should never pass a user's personal information in a url because urls are very leaky. Urls end up in log files, browsing histories, referal headers, etc. The list goes on and on.

As for proper url encoding, it can be achieved using either urlencode() or http_build_query(). Either one of these should work:

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);


$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;

Additionally, if $event_id is in your session, you don't actually need to pass it around in order to access it from different pages. Just call session_start() and it should be available.

What is the difference between signed and unsigned variables?

While commonly referred to as a 'sign bit', the binary values we usually use do not have a true sign bit.

Most computers use two's-complement arithmetic. Negative numbers are created by taking the one's-complement (flip all the bits) and adding one:

      5 (decimal) -> 00000101 (binary)
      1's complement: 11111010
      add 1: 11111011 which is 'FB' in hex

This is why a signed byte holds values from -128 to +127 instead of -127 to +127:

      1 0 0 0 0 0 0 0 = -128
      1 0 0 0 0 0 0 1 = -127
          - - -
      1 1 1 1 1 1 1 0 = -2
      1 1 1 1 1 1 1 1 = -1
      0 0 0 0 0 0 0 0 = 0
      0 0 0 0 0 0 0 1 = 1
      0 0 0 0 0 0 1 0 = 2
          - - -
      0 1 1 1 1 1 1 0 = 126
      0 1 1 1 1 1 1 1 = 127
      (add 1 to 127 gives:)
      1 0 0 0 0 0 0 0   which we see at the top of this chart is -128.

If we had a proper sign bit, the value range would be the same (e.g., -127 to +127) because one bit is reserved for the sign. If the most-significant-bit is the sign bit, we'd have:

      5 (decimal) -> 00000101 (binary)
      -5 (decimal) -> 10000101 (binary)

The interesting thing in this case is we have both a zero and a negative zero:
      0 (decimal) -> 00000000 (binary)
      -0 (decimal) -> 10000000 (binary)

We don't have -0 with two's-complement; what would be -0 is -128 (or to be more general, one more than the largest positive value). We do with one's complement though; all 1 bits is negative 0.

Mathematically, -0 equals 0. I vaguely remember a computer where -0 < 0, but I can't find any reference to it now.

Receiving "Attempted import error:" in react app

This is another option:

export default function Counter() {


Hashcode and Equals for Hashset

according jdk source code from, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                return oldValue;

        addEntry(hash, key, value, i);
        return null;

The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.

Hiding a password in a python script (insecure obfuscation only)

Place the configuration information in a encrypted config file. Query this info in your code using an key. Place this key in a separate file per environment, and don't store it with your code.

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

How can I check if a MySQL table exists with PHP?

It was already posted but here it is with PDO (same query)...

$connection = new PDO ( "mysql:host=host_db; dbname=name_db", user_db, pass_db );

if ($connection->query ("DESCRIBE table_name"  )) {
    echo "exist";
} else {
    echo "doesn't exist";

Works like a charm for me....

And here's another approach (i think it is slower)...

if ($connection->query ( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' AND table_name ='tbl_name'" )->fetch ()) {
    echo "exist";
} else {
    echo "doesn't exist";

You can also play with this query:

SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'

I think this was suggested to use in the mysql page.

How to use background thread in swift?

I really like Dan Beaulieu's answer, but it doesn't work with Swift 2.2 and I think we can avoid those nasty forced unwraps!

func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {


        if let completion = completion{
            let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
            dispatch_after(popTime, dispatch_get_main_queue()) {

How do I convert number to string and pass it as argument to Execute Process Task?

Cause of the issue:

Arguments property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR and not DT_STR.

SSIS 2008 R2 package illustrating the issue and fix:

Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx. Create a package variable with the following information.

Name   Scope        Data Type  Value
------ ------------ ---------- -----
IdVar  SO_13177007  Int32      123

Variables pane

Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments

Control Flow tab

Double-click the Execute Process Task to open the Execute Process Task Editor. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor.

Execute Process Task Editor

On the Property Expression Editor, select the property Arguments and click the Ellipsis button against the property to open the Expression Builder.

Property Expression Editor

On the Expression Builder, enter the following expression and click Evaluate Expression. This expression tries to convert the integer value in the variable IdVar to string data type.

(DT_STR, 10, 1252) @[User::IdVar]

Expression Builder - DT_STR

Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR.

Integer to ANSI string conversion error

To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR. Clicking Evaluate Expression will display the value in the Evaluated value text area.

(DT_WSTR, 10) @[User::IdVar]

Expression Builder - DT_WSTR


To understand the differences between the data types DT_STR and DT_WSTR in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.


A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)


A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

Generate random int value from 3 to 6

SELECT ROUND((6 - 3 * RAND()), 0)

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

  <base href="${baseURL}" />

How to use an environment variable inside a quoted string in Bash

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

echo "$VARIABLE"
echo "${VARIABLE}"

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).

Function of Project > Clean in Eclipse

There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

Make an Installation program for C# applications and include .NET Framework installer into the setup

You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.

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

The API return value in my case as shown here:

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

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

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

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

'Syntax Error: invalid syntax' for no apparent reason

You're missing a close paren in this line:


There are three ( and only two ).
I hope This will help you.

Passing data between view controllers

After more research it seemed that protocols and delegates were the correct/Apple preferred way of doing this.

I ended up using this example (in the iPhone development SDK):

Sharing data between view controllers and other objects

It worked fine and allowed me to pass a string and an array forward and back between my views.

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

CustomErrors mode="Off"

This has been driving me insane for the past few days and couldn't get around it but have finally figured it out:

In my machine.config file I had an entry under <system.web>:

<deployment retail="true" />

This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to:

<deployment retail="false" />

now means that I can once again see the detailed error messages that I need to.

The machine.config is located at





Hope that helps someone out there and saves a few hours of hair-pulling.

How to search a specific value in all tables (PostgreSQL)?

Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.

DO $$
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
  END; $$;


Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Getting Access Denied when calling the PutObject operation with bucket-level permission

If you have set public access for bucket and if it is still not working, edit bucker policy and paste following:

    "Version": "2012-10-17",
    "Statement": [
            "Action": [
            "Resource": [
            "Effect": "Allow",
            "Principal": "*"

Latex - Change margins of only a few pages

I could not find a easy way to set the margin for a single page.

My solution was to use vspace with the number of centimeters of empty space I wanted:


I put this command at the beginning of the pages that I wanted to have +5cm of margin.

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link


The activity's main window is always resized to make room for the soft keyboard on screen.


The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

Running sites on "localhost" is extremely slow

I had the same problem with PHP. I solved it by changing "localhost" to "" in database connection parameters like someone suggested here: . I think it may work for you too, give it a try.

What is the Gradle artifact dependency graph command?

Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being

 gradle :<subproject>:dependencies

so for me this was

 gradle :master:dependencies

Removing viewcontrollers from navigation stack

Swift 5, Xcode 11.3

I found this approach simple by specifying which view controller(s) you want to remove from the navigation stack.

extension UINavigationController {

    func removeViewController(_ controller: UIViewController.Type) {
        if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {

Example use:


html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

        <td colspan="2">75</td>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

i had same problem. I was run it on terminal with "sudo geany", you should run it without "sudo" just type on terminal "geany" and it is solved for me.

Oracle: how to UPSERT (update or insert into a table?)

The MERGE statement merges data between two tables. Using DUAL allows us to use this command. Note that this is not protected against concurrent access.

create or replace
procedure ups(xa number)
    merge into mergetest m using dual on (a = xa)
         when not matched then insert (a,b) values (xa,1)
             when matched then update set b = b+1;
end ups;
drop table mergetest;
create table mergetest(a number, b number);
call ups(10);
call ups(10);
call ups(20);
select * from mergetest;

A                      B
---------------------- ----------------------
10                     2
20                     1

Where is Developer Command Prompt for VS2013?

enter image description here

You can simply go to Menu > All Programs > Visual Studio 2013. Select the folder link "Visual Studio Tools". This will open the folder. There is bunch of shortcuts for command prompt which you can use. They worked perfectly for me.

I think the trick here might be there are different versions for different processors, hence they put them all together.

Merge, update, and pull Git branches without using checkouts

The Short Answer

As long as you're doing a fast-forward merge, then you can simply use

git fetch <remote> <sourceBranch>:<destinationBranch>


# Merge local branch foo into local branch master,
# without having to checkout master first.
# Here `.` means to use the local repository as the "remote":
git fetch . foo:master

# Merge remote branch origin/foo into local branch foo,
# without having to checkout foo first:
git fetch origin foo:foo

While Amber's answer will also work in fast-forward cases, using git fetch in this way instead is a little safer than just force-moving the branch reference, since git fetch will automatically prevent accidental non-fast-forwards as long as you don't use + in the refspec.

The Long Answer

You cannot merge a branch B into branch A without checking out A first if it would result in a non-fast-forward merge. This is because a working copy is needed to resolve any potential conflicts.

However, in the case of fast-forward merges, this is possible, because such merges can never result in conflicts, by definition. To do this without checking out a branch first, you can use git fetch with a refspec.

Here's an example of updating master (disallowing non-fast-forward changes) if you have another branch feature checked out:

git fetch upstream master:master

This use-case is so common, that you'll probably want to make an alias for it in your git configuration file, like this one:

    sync = !sh -c 'git checkout --quiet HEAD; git fetch upstream master:master; git checkout --quiet -'

What this alias does is the following:

  1. git checkout HEAD: this puts your working copy into a detached-head state. This is useful if you want to update master while you happen to have it checked-out. I think it was necessary to do with because otherwise the branch reference for master won't move, but I don't remember if that's really right off-the-top of my head.

  2. git fetch upstream master:master: this fast-forwards your local master to the same place as upstream/master.

  3. git checkout - checks out your previously checked-out branch (that's what the - does in this case).

The syntax of git fetch for (non-)fast-forward merges

If you want the fetch command to fail if the update is non-fast-forward, then you simply use a refspec of the form

git fetch <remote> <remoteBranch>:<localBranch>

If you want to allow non-fast-forward updates, then you add a + to the front of the refspec:

git fetch <remote> +<remoteBranch>:<localBranch>

Note that you can pass your local repo as the "remote" parameter using .:

git fetch . <sourceBranch>:<destinationBranch>

The Documentation

From the git fetch documentation that explains this syntax (emphasis mine):


The format of a <refspec> parameter is an optional plus +, followed by the source ref <src>, followed by a colon :, followed by the destination ref <dst>.

The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref that matches it is fast-forwarded using <src>. If the optional plus + is used, the local ref is updated even if it does not result in a fast-forward update.

See Also

  1. Git checkout and merge without touching working tree

  2. Merging without changing the working directory