Programs & Examples On #Buzzword compliance

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

creating custom tableview cells in swift

It is Purely swift notation an working for me

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cellIdentifier:String = "CustomFields"
        var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
        if (cell == nil)
        {
            var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
            cell = nib[0] as? CustomCell
        }
        return cell!
    }

How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in ng-model.

How to terminate a window in tmux?

Generally:

tmux kill-window -t window-number

So for example, if you are in window 1 and you want to kill window 9:

tmux kill-window -t 9

How to set environment via `ng serve` in Angular 6

Use this command for Angular 6 to build

ng build --prod --configuration=dev

Clearing a text field on button click

A simple JavaScript function will do the job.

function ClearFields() {

     document.getElementById("textfield1").value = "";
     document.getElementById("textfield2").value = "";
}

And just have your button call it:

<button type="button" onclick="ClearFields();">Clear</button>

symbol(s) not found for architecture i386

This happened to me while trying to copy over the PSPDFKIT demo library into my project. I followed all the instructions in the site + all the suggestions on this page.. for some reason it kept on giving the above error, the problem was that if i grepped the message in the error method.. it only appeared in the binary (obviously I have no access to the source code b/c I have to pay for it).

I noticed this in the instruction page though:

enter image description here

So I went to the guts of that config file and found this:

OTHER_LDFLAGS=$(inherited) -ObjC -fobjc-arc -lz -framework CoreText -framework CoreMedia -framework MediaPlayer -framework AVFoundation -framework ImageIO -framework MediaPlayer -framework MessageUI -framework CoreGraphics -framework Foundation -framework QuartzCore -framework AVFoundation -framework CFNetwork -framework MobileCoreServices -framework SystemConfiguration -weak_framework UIKit

Then I went to the sample project provided by the author of the said library.. and noticed that the previous flags where copied verbatim to the other linker flags in my build settings.. however in my project.. they were not!.. So i simply copied and pasted them into my project's build settings other linker flags and everything worked!

take away point: if you are relying on some .xcconfig file on your setup, double check with a sample code source or something and make sure that it has actually been applied.. it wasn't applied properly in my case

How to replace plain URLs with links?

Try Below Solution

function replaceLinkClickableLink(url = '') {
let pattern = new RegExp('^(https?:\\/\\/)?'+
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+
        '((\\d{1,3}\\.){3}\\d{1,3}))'+
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
        '(\\?[;&a-z\\d%_.~+=-]*)?'+
        '(\\#[-a-z\\d_]*)?$','i');

let isUrl = pattern.test(url);
if (isUrl) {
    return `<a href="${url}" target="_blank">${url}</a>`;
}
return url;
}

Add custom message to thrown exception while maintaining stack trace in Java

There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}

Is it possible to do a sparse checkout without checking out the whole repository first?

I found the answer I was looking for from the one-liner posted earlier by pavek (thanks!) so I wanted to provide a complete answer in a single reply that works on Linux (GIT 1.7.1):

1--> mkdir myrepo
2--> cd myrepo
3--> git init
4--> git config core.sparseCheckout true
5--> echo 'path/to/subdir/' > .git/info/sparse-checkout
6--> git remote add -f origin ssh://...
7--> git pull origin master

I changed the order of the commands a bit but that does not seem to have any impact. The key is the presence of the trailing slash "/" at the end of the path in step 5.

performSelector may cause a leak because its selector is unknown

You could also use a protocol here. So, create a protocol like so:

@protocol MyProtocol
-(void)doSomethingWithObject:(id)object;
@end

In your class that needs to call your selector, you then have a @property.

@interface MyObject
    @property (strong) id<MyProtocol> source;
@end

When you need to call @selector(doSomethingWithObject:) in an instance of MyObject, do this:

[self.source doSomethingWithObject:object];

How do the post increment (i++) and pre increment (++i) operators work in Java?

In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it

++a

  1. a = a + 1;
  2. return a;

a++

  1. temp = a;
  2. a = a + 1;
  3. return temp;

Labeling file upload button

Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.

It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.

There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:

  • To a screen reader, the file control will still say "Browse..." or "Choose File", and a custom file upload will not be announced as a file upload control, but just a button or a text input.
  • Many of them fail to display the chosen file, or to show that the user has no longer chosen a file
  • Many of them look nothing like the native control, so might look strange on non-standard devices.
  • Keyboard support is typically poor.
  • An author-created UI component can never be as fully functional as its native equivalent (and the closer you get it to behave to suppose IE10 on Windows 7, the more it will deviate from other Browser and Operating System combinations).
  • Modern browsers support drag & drop into the native file upload control.
  • Some techniques may trigger heuristics in security software as a potential ‘click-jacking’ attempt to trick the user into uploading file.

Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.

However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.

Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?

The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).

Sorry. :-(

--

This answer is for those looking for any justification not to localise the file upload control.

How to read and write INI file with Python3?

ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:

  • Nested sections (subsections), to any level
  • List values
  • Multiple line values
  • String interpolation (substitution)
  • Integrated with a powerful validation system including automatic type checking/conversion repeated sections and allowing default values
  • When writing out config files, ConfigObj preserves all comments and the order of members and sections
  • Many useful methods and options for working with configuration files (like the 'reload' method)
  • Full Unicode support

It has some draw backs:

  • You cannot set the delimiter, it has to be =… (pull request)
  • You cannot have empty values, well you can but they look liked: fuabr = instead of just fubar which looks weird and wrong.

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

Set Culture in an ASP.Net MVC app

I know this is an old question, but if you really would like to have this working with your ModelBinder (in respect to DefaultModelBinder.ResourceClassKey = "MyResource"; as well as the resources indicated in the data annotations of the viewmodel classes), the controller or even an ActionFilter is too late to set the culture.

The culture could be set in Application_AcquireRequestState, for example:

protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        // For example a cookie, but better extract it from the url
        string culture = HttpContext.Current.Request.Cookies["culture"].Value;

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
    }

EDIT

Actually there is a better way using a custom routehandler which sets the culture according to the url, perfectly described by Alex Adamyan on his blog.

All there is to do is to override the GetHttpHandler method and set the culture there.

public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // get culture from route data
        var culture = requestContext.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
        return base.GetHttpHandler(requestContext);
    }
}

How to get certain commit from GitHub project

write this to see your commits

git log --oneline

copy the name of the commit you want to go back to. then write:

git checkout "name of the commit"

when you do this, the files of that commit will be replaced with your current files. then you can do whatever you want to these and once you're done, you can write the following command to extract the current files into another newly created branch so whatever you make doesn't have any danger for the previous branch that you extracted a commit from

git checkout -b "name of a branch to extract the files to"

right now, you have the content of a specified commit, into another branch .

Run Command Prompt Commands

This can also be done by P/Invoking the C standard library's system function.

using System.Runtime.InteropServices;

[DllImport("msvcrt.dll")]
public static extern int system(string format);

system("copy Test.txt Test2.txt");

Output:

      1 file(s) copied.

What exactly does stringstream do?

You entered an alphanumeric and int, blank delimited in mystr.

You then tried to convert the first token (blank delimited) into an int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

When you only entered int values the second time, everything worked as you expected.

It was the spurious RS that caused your code to fail.

How to convert an address into a Google Maps Link (NOT MAP)

How about this?

https://maps.google.com/?q=1200 Pennsylvania Ave SE, Washington, District of Columbia, 20003

https://maps.google.com/?q=term

If you have lat-long then use below URL

https://maps.google.com/?ll=latitude,longitude

Example: maps.google.com/?ll=38.882147,-76.99017

UPDATE

As of year 2017, Google now has an official way to create cross-platform Google Maps URLs:

https://developers.google.com/maps/documentation/urls/guide

You can use links like

https://www.google.com/maps/search/?api=1&query=1200%20Pennsylvania%20Ave%20SE%2C%20Washington%2C%20District%20of%20Columbia%2C%2020003 

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

Android 6.0 Marshmallow. Cannot write to SD Card

Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:

Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().


I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.

You can define the max sdk version in the manifest per permission like:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />

Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}

'dependencies.dependency.version' is missing error, but version is managed in parent

You must build parent module before doing child module.

How do I rename a column in a database table using SQL?

In MySQL, the syntax is ALTER TABLE ... CHANGE:

ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...

Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Number of processors/cores in command line

If you want to do this so it works on linux and OS X, you can do:

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

Python: Append item to list N times

Itertools repeat combined with list extend.

from itertools import repeat
l = []
l.extend(repeat(x, 100))

How to set xampp open localhost:8080 instead of just localhost

Steps using XAMPP GUI:

Step-1: Click on Config button

enter image description here

Step-2: Click on Service and Port Settings button

enter image description here

Final step: Change your port and Save

enter image description here

Border for an Image view in Android?

Just add this code in your ImageView:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/white"/>

    <size
        android:width="20dp"
        android:height="20dp"/>
    <stroke
        android:width="4dp" android:color="@android:color/black"/>
    <padding android:left="1dp" android:top="1dp" android:right="1dp"
        android:bottom="1dp" />
</shape>

How to auto adjust the <div> height according to content in it?

I've used the following in the DIV that needs to be resized:

overflow: hidden;
height: 1%;

Fastest method to replace all instances of a character in a string

Try this replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8

String.prototype.replaceAll = function(str1, str2, ignore) 
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} 

It is very fast, and it will work for ALL these conditions that many others fail on:

"x".replaceAll("x", "xyz");
// xyz

"x".replaceAll("", "xyz");
// xyzxxyz

"aA".replaceAll("a", "b", true);
// bb

"Hello???".replaceAll("?", "!");
// Hello!!!

Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Java Runtime.getRuntime(): getting output from executing a command line program

Also we can use streams for obtain command output:

public static void main(String[] args) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How to start color picker on Mac OS?

You can turn the color picker into an application by following the guide here:

http://hints.macworld.com/article.php?story=20060408050920158

From the guide:

Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:

choose color

Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done

How to discard all changes made to a branch?

In the source root: git reset ./ HEAD <--un-stage any staged changes git checkout ./ <--discard any unstaged changes

Loading resources using getClass().getResource()

getResource by example:

package szb.testGetResource;
public class TestGetResource {
    private void testIt() {
        System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
        System.out.println("test2: "+getClass().getResource("test.css"));
    }
    public static void main(String[] args) {
        new TestGetResource().testIt();
    }
}

enter image description here

output:

test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css

How to turn off caching on Firefox?

Enter "about:config" into the Firefox address bar and set:

browser.cache.disk.enable = false
browser.cache.memory.enable = false

If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config -

browser.cache.offline.enable = false

How do I find all the files that were created today in Unix/Linux?

After going through may posts i found the best one that really works

find $file_path -type f -name "*.txt" -mtime -1 -printf "%f\n"

This prints only the file name like abc.txt not the /path/tofolder/abc.txt

Also also play around or customize with -mtime -1

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

How to convert all tables in database to one collation?

If you're using PhpMyAdmin, you can now:

  1. Select the database.
  2. Click the "Operations" tab.
  3. Under "Collation" section, select the desired collation.
  4. Click the "Change all tables collations" checkbox.
  5. A new "Change all tables columns collations" checkbox will appear.
  6. Click the "Change all tables columns collations" checkbox.
  7. Click the "Go" button.

I had over 250 tables to convert. It took a little over 5 minutes.

Centering a canvas

Wrapping it with div should work. I tested it in Firefox, Chrome on Fedora 13 (demo).

#content {
   width: 95%;
   height: 95%;
   margin: auto;
}

#myCanvas {
   width: 100%;
   height: 100%;
   border: 1px solid black;
}

And the canvas should be enclosed in tag

<div id="content">
    <canvas id="myCanvas">Your browser doesn't support canvas tag</canvas>
</div>

Let me know if it works. Cheers.

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Dynamically updating css in Angular 2

Try this

 <div class="home-component" 
 [style.width.px]="width" 
 [style.height.px]="height">Some stuff in this div</div>

[Updated]: To set in % use

[style.height.%]="height">Some stuff in this div</div>

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

import itertools
import collections

dictA = {'a':1, 'b':2, 'c':3}
dictB = {'b':3, 'c':4, 'd':5}

new_dict = collections.defaultdict(int)
# use dict.items() instead of dict.iteritems() for Python3
for k, v in itertools.chain(dictA.iteritems(), dictB.iteritems()):
    new_dict[k] += v

print dict(new_dict)

# OUTPUT
{'a': 1, 'c': 7, 'b': 5, 'd': 5}

OR

Alternative you can use Counter as @Martijn has mentioned above.

How to echo out table rows from the db (php)

Nested loop to display all rows & columns of resulting table:

$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
   for( $j = 0; $j<$cols; $j++ ) {
     echo mysql_result($result, $i, $j)."<br>";
   }
}

Can be made more complex with data decryption/decoding, error checking & html formatting before display.

Tested in MS Edge & G Chrome, PHP 5.6

error: This is probably not a problem with npm. There is likely additional logging output above

Check if port you want to run your app is free. For me, it was the problem.

What's a simple way to get a text input popup dialog box on an iPhone

Building on John Riselvato's answer, to retrieve the string back from the UIAlertView...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })

Find distance between two points on map using Google Map API V2

This is an old question with old answers. I want to highlight an updated way of calculating distance between two points. By now we should be familiar with the utility class, "SphericalUtil". You can retrieve the distance using that.

double distance = SphericalUtil.computeDistanceBetween(origin, dest);

Get type of a generic parameter in Java with reflection

You can get the type of a generic parameter with reflection like in this example that I found here:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Home<E> {
    @SuppressWarnings ("unchecked")
    public Class<E> getTypeParameterClass(){
        Type type = getClass().getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) type;
        return (Class<E>) paramType.getActualTypeArguments()[0];
    }

    private static class StringHome extends Home<String>{}
    private static class StringBuilderHome extends Home<StringBuilder>{}
    private static class StringBufferHome extends Home<StringBuffer>{}   

    /**
     * This prints "String", "StringBuilder" and "StringBuffer"
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Object object0 = new StringHome().getTypeParameterClass().newInstance();
        Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
        Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
        System.out.println(object0.getClass().getSimpleName());
        System.out.println(object1.getClass().getSimpleName());
        System.out.println(object2.getClass().getSimpleName());
    }
}

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

How can I escape square brackets in a LIKE clause?

I needed to exclude names that started with an underscore from a query, so I ended up with this:

WHERE b.[name] not like '\_%' escape '\'  -- use \ as the escape character

How to convert a List<String> into a comma separated string without iterating List explicitly

If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));

Note: I am a committer for Eclipse collections.

jQuery SVG vs. Raphael

I will throw my vote behind Raphael - the cross-browser support, clean API and consistent updates (so far) make it a joy to use. It plays very nicely with jQuery too. Processing is cool, but more useful as a demo for bleeding-edge stuff at the moment.

Javascript: how to validate dates in format MM-DD-YYYY?

try this:

function validateDate(dates){
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;     
    var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);

            if(regs = dates.match(re)) {
                    // day value between 1 and 31
                    if(regs[1] < 1 || regs[1] > 31) {                    
                      return false;
                    }
                    // month value between 1 and 12
                    if(regs[2] < 1 || regs[2] > 12) {                         
                      return false;
                    }

                    var maxday=days[regs[2]-1];

                    if(regs[2]==2){
                        if(regs[3]%4==0){
                            maxday=maxday+1;                                
                        }
                    }

                    if(regs[1]>maxday){
                        return false;
                    }

                    return true;
              }else{
                  return false;
              }                   
}

Display animated GIF in iOS

FLAnimatedImage is a performant open source animated GIF engine for iOS:

  • Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers
  • Honors variable frame delays
  • Behaves gracefully under memory pressure
  • Eliminates delays or blocking during the first playback loop
  • Interprets the frame delays of fast GIFs the same way modern browsers do

It's a well-tested component that I wrote to power all GIFs in Flipboard.

How to make CSS3 rounded corners hide overflow in Chrome/Opera

I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.

#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */

/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}

#box {
width: 300px; height: 300px;
background-color: #cde;
}?

JSFiddle Example

Show Curl POST Request Headers? Is there a way to do this?

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Turning a Comma Separated string into individual rows

As of Feb 2016 - see the TALLY Table Example - very likely to outperform my TVF below, from Feb 2014. Keeping original post below for posterity:


Too much repeated code for my liking in the above examples. And I dislike the performance of CTEs and XML. Also, an explicit Id so that consumers that are order specific can specify an ORDER BY clause.

CREATE FUNCTION dbo.Split
(
    @Line nvarchar(MAX),
    @SplitOn nvarchar(5) = ','
)
RETURNS @RtnValue table
(
    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    Data nvarchar(100) NOT NULL
)
AS
BEGIN
    IF @Line IS NULL RETURN

    DECLARE @split_on_len INT = LEN(@SplitOn)
    DECLARE @start_at INT = 1
    DECLARE @end_at INT
    DECLARE @data_len INT

    WHILE 1=1
    BEGIN
        SET @end_at = CHARINDEX(@SplitOn,@Line,@start_at)
        SET @data_len = CASE @end_at WHEN 0 THEN LEN(@Line) ELSE @end_at-@start_at END
        INSERT INTO @RtnValue (data) VALUES( SUBSTRING(@Line,@start_at,@data_len) );
        IF @end_at = 0 BREAK;
        SET @start_at = @end_at + @split_on_len
    END

    RETURN
END

Generating random integer from a range

The following expression should be unbiased if I am not mistaken:

std::floor( ( max - min + 1.0 ) * rand() ) + min;

I am assuming here that rand() gives you a random value in the range between 0.0 and 1.0 NOT including 1.0 and that max and min are integers with the condition that min < max.

Prevent cell numbers from incrementing in a formula in Excel

TL:DR
row lock = A$5
column lock = $A5
Both = $A$5

Below are examples of how to use the Excel lock reference $ when creating your formulas

To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5

To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5

To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5

Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.

How do I test if a recordSet is empty? isNull?

If Not temp_rst1 Is Nothing Then ...

How to install MySQLi on MacOS

sudo apt-get -y -f install php7.0-mysql

Using union and order by clause in mysql

Don't forget, union all is a way to add records to a record set without sorting or merging (as opposed to union).

So for example:

select * from (
    select col1, col2
    from table a
    <....>
    order by col3
    limit by 200
) a
union all
select * from (
    select cola, colb
    from table b
    <....>
    order by colb
    limit by 300
) b

It keeps the individual queries clearer and allows you to sort by different parameters in each query. However by using the selected answer's way it might become clearer depending on complexity and how related the data is because you are conceptualizing the sort. It also allows you to return the artificial column to the querying program so it has a context it can sort by or organize.

But this way has the advantage of being fast, not introducing extra variables, and making it easy to separate out each query including the sort. The ability to add a limit is simply an extra bonus.

And of course feel free to turn the union all into a union and add a sort for the whole query. Or add an artificial id, in which case this way makes it easy to sort by different parameters in each query, but it otherwise is the same as the accepted answer.

internal/modules/cjs/loader.js:582 throw err

  1. Delete the node_modules directory
  2. Delete the package-lock.json file
  3. Run npm install
  4. Run npm start

OR

rm -rf node_modules package-lock.json && npm install && npm start

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Difference between number and integer datatype in oracle dictionary views

the best explanation i've found is this:

What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...

NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.

  • INTEGER(12.2) => 12
  • INTEGER(12.5) => 13
  • INTEGER(12.9) => 13
  • INTEGER(12.4) => 12
  • NUMBER(12.2) => 12.2
  • NUMBER(12.5) => 12.5
  • NUMBER(12.9) => 12.9
  • NUMBER(12.4) => 12.4

INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.

Here is the link

How to hide "Showing 1 of N Entries" with the dataTables.js library

Now, this seems to work:

$('#example').DataTable({
  "info": false
});

it hides that div, altogether

How to use activity indicator view on iPhone?

- (IBAction)toggleSpinner:(id)sender
{
    if (self.spinner.isAnimating)
    {
        [self.spinner stopAnimating];
        ((UIButton *)sender).titleLabel.text = @"Start spinning";
        [self.controlState setValue:[NSNumber numberWithBool:NO] forKey:@"SpinnerAnimatingState"];
    }
    else
    {
        [self.spinner startAnimating];
        ((UIButton *)sender).titleLabel.text = @"Stop spinning";
        [self.controlState setValue:[NSNumber numberWithBool:YES] forKey:@"SpinnerAnimatingState"];
    }
}

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

How to change row color in datagridview?

You're looking for the CellFormatting event.
Here is an example.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Basic HTTP and Bearer Token Authentication

If you are using a reverse proxy such as nginx in between, you could define a custom token, such as X-API-Token.

In nginx you would rewrite it for the upstream proxy (your rest api) to be just auth:

proxy_set_header Authorization $http_x_api_token;

... while nginx can use the original Authorization header to check HTTP AUth.

Javac is not found

do this: 1. run CMD (WIN+R then type in CMD) 2. Type this:

set PATH=%PATH%; java installation path\bin

Replace "java installation path" with the directory JDK is installed in, such as C:\Program Files (x86)\Java. Be sure to add the \bin after the JDK directory, because this points to "javac" and "java" (BIN stands for "binaries")

This way, you can run the Java compiler from anywhere. It is impossible to CD to the JDK directory because it has a space in Program Files, and DOS will not let you CD to these directories.

Who is listening on a given TCP port on Mac OS X?

on OS X you can use the -v option for netstat to give the associated pid.

type:

netstat -anv | grep [.]PORT

the output will look like this:

tcp46      0      0  *.8080                 *.*                    LISTEN      131072 131072   3105      0

The PID is the number before the last column, 3105 for this case

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If you're seeing this error message when attempting to connect using SSMS, add TrustServerCertificate=True to the Additional Connection Parameters.

Parsing JSON from URL

I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class can be also a complex type. Just for example used.

No restricted globals

Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.

import React from 'react';
import withRouter from 'react-router-dom';

const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)


export withRouter(MyComponent);

CSS background image alt attribute

It''s not clear to me what you want.

If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:

IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.

Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

How to read a file in reverse order?

Thanks for the answer @srohde. It has a small bug checking for newline character with 'is' operator, and I could not comment on the answer with 1 reputation. Also I'd like to manage file open outside because that enables me to embed my ramblings for luigi tasks.

What I needed to change has the form:

with open(filename) as fp:
    for line in fp:
        #print line,  # contains new line
        print '>{}<'.format(line)

I'd love to change to:

with open(filename) as fp:
    for line in reversed_fp_iter(fp, 4):
        #print line,  # contains new line
        print '>{}<'.format(line)

Here is a modified answer that wants a file handle and keeps newlines:

def reversed_fp_iter(fp, buf_size=8192):
    """a generator that returns the lines of a file in reverse order
    ref: https://stackoverflow.com/a/23646049/8776239
    """
    segment = None  # holds possible incomplete segment at the beginning of the buffer
    offset = 0
    fp.seek(0, os.SEEK_END)
    file_size = remaining_size = fp.tell()
    while remaining_size > 0:
        offset = min(file_size, offset + buf_size)
        fp.seek(file_size - offset)
        buffer = fp.read(min(remaining_size, buf_size))
        remaining_size -= buf_size
        lines = buffer.splitlines(True)
        # the first line of the buffer is probably not a complete line so
        # we'll save it and append it to the last line of the next buffer
        # we read
        if segment is not None:
            # if the previous chunk starts right from the beginning of line
            # do not concat the segment to the last line of new chunk
            # instead, yield the segment first
            if buffer[-1] == '\n':
                #print 'buffer ends with newline'
                yield segment
            else:
                lines[-1] += segment
                #print 'enlarged last line to >{}<, len {}'.format(lines[-1], len(lines))
        segment = lines[0]
        for index in range(len(lines) - 1, 0, -1):
            if len(lines[index]):
                yield lines[index]
    # Don't yield None if the file was empty
    if segment is not None:
        yield segment

Make a UIButton programmatically in Swift

You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = UIColor.redColor()
    myFirstLabel.textAlignment = .Center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
    myFirstButton.setTitle("?", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

@objc func pressed(sender: UIButton!) {
    var alertView = UIAlertView()
    alertView.addButtonWithTitle("Ok")
    alertView.title = "title"
    alertView.message = "message"
    alertView.show()
}

EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

How to remove gem from Ruby on Rails application?

How about something like:

gem dependency devise --pipe | cut -d \  -f 1 | xargs gem uninstall -a

(this assumes that you're not using bundler - but I guess you're not since removing from your bundle gemspec would solve the problem)

Regular expression matching a multiline block of text

Try this:

re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)

I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.

Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:

re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)

BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Anyone else who is struggling with this, there is a very simple "inline" way to do this with jQuery:

<input type="search" placeholder="Search" value="" maxlength="256" id="q" name="q" style="width: 300px;" onChange="$('#ADSearch').attr('value', $('#q').attr('value'))"><input type="hidden" name="ADSearch" id="ADSearch" value="">

This sets the value of the hidden field as text is typed into the visible input using the onChange event. Helpful (like in my case) where you want to pass on a field value to an "Advanced Search" form and not force the user to re-type their search query.

Do C# Timers elapse on a separate thread?

For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.

    static System.Timers.Timer DummyTimer = null;

    static void Main(string[] args)
    {
        try
        {

            Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
            DummyTimer.Enabled = true;
            DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
            DummyTimer.AutoReset = true;

            DummyTimer.Start();

            Console.WriteLine("Hit any key to exit");
            Console.ReadLine();
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
        }

        return;
    }

    static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
        return;
    }

Output you'd see if DummyTimer fired on 5 seconds interval:

Main Thread Id: 9
   12
   12
   12
   12
   12
   ... 

So, as seen, OnDummyTimerFired is executed on Workers thread.

No, further complication - If you reduce interval to say 10 ms,

Main Thread Id: 9
   11
   13
   12
   22
   17
   ... 

This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.

Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx#S2

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

how to install apk application from my pc to my mobile android

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>

We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan

AngularJS ngClass conditional

There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.

<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>

Happy Coding, Nimantha Perera

How to input a regex in string.replace?

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

How to configure PHP to send e-mail?

You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.

If you own a server or VPS upload the script and it will work fine.

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Retrieving Property name from lambda expression

I created an extension method on ObjectStateEntry to be able to flag properties (of Entity Framework POCO classes) as modified in a type safe manner, since the default method only accepts a string. Here's my way of getting the name from the property:

public static void SetModifiedProperty<T>(this System.Data.Objects.ObjectStateEntry state, Expression<Func<T>> action)
{
    var body = (MemberExpression)action.Body;
    string propertyName = body.Member.Name;

    state.SetModifiedProperty(propertyName);
}

Round a divided number in Bash

Another solution is to do the division within a python command. For example:

$ numerator=90
$ denominator=7
$ python -c "print (round(${numerator}.0 / ${denominator}.0))"

Seems less archaic to me than using awk.

Android Studio - local path doesn't exist

Heh tried all these answers and none of them worked. I think a common cause of this issue is something a lot simpler.

I advise all who get this problem to look at their launch configuration:

Launch Configuration

Look! The launch configuration contains options for which APK to deploy. If you choose default, Android Studio will be dumb to any product flavors, build types etc. you have in your gradle file. In my case, I have multiple build types and product flavors, and received "no local path" when trying to launch a non-default product flavor.

Android Studio was not wrong! It couldn't find the default APK, because I was not building for it. I solve my issue by instead choosing "Do not deploy anything" and then executing the gradle install task I needed for my specific combination of product flavor / build type.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

How can I export a GridView.DataSource to a datatable or dataset?

You should convert first DataSource in BindingSource, look example

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;

With the data of tCxC you can do anything.

In Java, how do I check if a string contains a substring (ignoring case)?

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).

Building on some of the above examples:

public boolean containsIgnoreCase( String haystack, String needle ) {
  if(needle.equals(""))
    return true;
  if(haystack == null || needle == null || haystack .equals(""))
    return false; 

  Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
  Matcher m = p.matcher(haystack);
  return m.find();
}

example call: 

String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
  System.out.println( "Found " + needle + " within " + haystack + "." );
}

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

How to copy file from HDFS to the local file system

If your source "file" is split up among multiple files (maybe as the result of map-reduce) that live in the same directory tree, you can copy that to a local file with:

hadoop fs -getmerge /hdfs/source/dir_root/ local/destination

Bootstrap: How do I identify the Bootstrap version?

You can locate it in the doc Block from bootstrap.min.css, at the top part.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

You need to use passive mode.

If you're using linux client, use pftp or ftp -p.

From man ftp:

-p    Use passive mode for data transfers. Allows use of ftp in environments where a firewall prevents connections from the outside world back to the client machine. Requires that the ftp server support the PASV command. This is the default if invoked as pftp.

CSS Float: Floating an image to the left of the text

I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)

.post-container {
 margin: 20px 20px 0 0;
 border:5px solid #333;
}
.post-thumb img {
 float: left;
}
.post-content {
 overflow:hidden;
}

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in GridView2.Rows)
            {
                if ( ! row.IsNewRow)
                {
                    for (int i = 0; i < GridView2.Columns.Count; i++)
                    {
                        String header = GridView2.Columns[i].HeaderText;
                        String cellText = Convert.ToString(row.Cells[i].Value);
                    }
                }
            }

Here Before Iterating for cell Values need to check for NewRow.

Can Mockito stub a method without regard to the argument?

when(
  fooDao.getBar(
    any(Bazoo.class)
  )
).thenReturn(myFoo);

or (to avoid nulls):

when(
  fooDao.getBar(
    (Bazoo)notNull()
  )
).thenReturn(myFoo);

Don't forget to import matchers (many others are available):

For Mockito 2.1.0 and newer:

import static org.mockito.ArgumentMatchers.*;

For older versions:

import static org.mockito.Matchers.*;

Can't use SURF, SIFT in OpenCV

None of the above suggested solutions worked for me. I use Anaconda and found that opencv version 3.3.1 still had Sift enabled. If you want to test in isolated conda environment, try the following inspired from @A.Ametov's answer above

conda create -n testenv opencv=3.3.1     
conda activate testenv

conda activate myenv
python
#Check version of opencv being used
>>> import cv2
>>> cv2.__version__
#Check if Sift is available
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

Difference between string and StringBuilder in C#

A StringBuilder will help you when you need to build strings in multiple steps.

Instead of doing this:

String x = "";
x += "first ";
x += "second ";
x += "third ";

you do

StringBuilder sb = new StringBuilder("");
sb.Append("first ");
sb.Append("second ");
sb.Append("third");
String x = sb.ToString();

The final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.

Is there a difference between using a dict literal and a dict constructor?

From python 2.7 tutorial:

A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

tel = {'jack': 4098, 'sape': 4139}
data = {k:v for k,v in zip(xrange(10), xrange(10,20))}

While:

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

dict(sape=4139, guido=4127, jack=4098)
>>>  {'sape': 4139, 'jack':4098, 'guido': 4127}

So both {} and dict() produce dictionary but provide a bit different ways of dictionary data initialization.

How to resize Image in Android?

bm = Bitmap.createScaledBitmap(bitmapSource, width, height, true);

:)

Include php files when they are in different folders

None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):

<?php
     $footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
     include($footerFile);
?>

Database corruption with MariaDB : Table doesn't exist in engine

Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.

UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

Python + Django page redirect

If you want to redirect a whole subfolder, the url argument in RedirectView is actually interpolated, so you can do something like this in urls.py:

from django.conf.urls.defaults import url
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]

The ?P<path> you capture will be fed into RedirectView. This captured variable will then be replaced in the url argument you gave, giving us /new_path/yay/mypath if your original path was /old/yay/mypath.

You can also do ….as_view(url='…', query_string=True) if you want to copy the query string over as well.

jQuery select2 get value of select tag?

Try this :

$('#input_id :selected').val(); //for getting value from selected option
$('#input_id :selected').text(); //for getting text from selected option

How to generate random colors in matplotlib?

When less than 9 datasets:

colors = "bgrcmykw"
color_index = 0

for X,Y in data:
    scatter(X,Y, c=colors[color_index])
    color_index += 1

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

matplotlib has no attribute 'pyplot'

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

It's useful in situations where you have hidden internal state such as a cache. For example:

class HashTable
{
...
public:
    string lookup(string key) const
    {
        if(key == lastKey)
            return lastValue;

        string value = lookupInternal(key);

        lastKey = key;
        lastValue = value;

        return value;
    }

private:
    mutable string lastKey, lastValue;
};

And then you can have a const HashTable object still use its lookup() method, which modifies the internal cache.

Typescript ReferenceError: exports is not defined

If you are just using interfaces for types, leave out the export keyword and ts can pick up on the types without needing to import. They key is you cannot use import/export anywhere.

export interface Person {
   name: string;
   age: number;
}

into

interface Person {
   name: string;
   age: number;
}

'sprintf': double precision in C

The problem is with sprintf

sprintf(aa,"%lf",a);

%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:

sprintf(aa, "%f", a);

More details here on cplusplus.com

How to programmatically set drawableLeft on Android button?

Try this:

((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

How can I use getSystemService in a non-activity class (LocationManager)?

I don't know if this will help, but I did this:

LocationManager locationManager  = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

Different color for each bar in a bar chart; ChartJS

As of August 2019, Chart.js now has this functionality built in.

Successful bar chart with different colored bars

You simply need to provide an array to backgroundColor.

Example taken from https://www.chartjs.org/docs/latest/getting-started/

Before:

  data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

After:

  data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: ['rgb(255, 99, 132)','rgb(0, 255, 0)','rgb(255, 99, 132)','rgb(128, 255, 0)','rgb(0, 255, 255)','rgb(255, 255, 0)','rgb(255, 255, 128)'],
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

I just tested this method and it works. Each bar has a different color.

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

How to split comma separated string using JavaScript?

var array = string.split(',')

and good morning, too, since I have to type 30 chars ...

How to determine if a type implements an interface with C# reflection

what about

if(MyType as IMyInterface != null)

?

Add space between <li> elements

add:

margin: 0 0 3px 0;

to your #access li and move

background: #0f84e8; /* Show a solid color for older browsers */

to the #access a and take out the border-bottom. Then it will work

Here: http://jsfiddle.net/bpmKW/4/

How to format a JavaScript date

If you need to quickly format your date using plain JavaScript, use getDate, getMonth + 1, getFullYear, getHours and getMinutes:

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50

Or, if you need it to be padded with zeros:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50

linux find regex

Well, you may try this '.*[0-9]'

ASP.Net which user account running Web Service on IIS 7?

You are most likely looking for the IIS_IUSRS account.

Create a tar.xz in one command

If you like the pipe mode, this is the most clean solution:

tar c some-dir | xz > some-dir.tar.xz

It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.

It works with gzip and bzip2 too:

tar c some-dir | gzip > some-dir.tar.gz

or

tar c some-dir | bzip2 > some-dir.tar.bz2

Decompressing is also quite straightforward:

xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x

If you have only tar archive, you can use cat:

cat archive.tar | tar x

If you need to list the files only, use tar t.

Using context in a fragment

Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity().

What is the difference between `sorted(list)` vs `list.sort()`?

The main difference is that sorted(some_list) returns a new list:

a = [3, 2, 1]
print sorted(a) # new list
print a         # is not modified

and some_list.sort(), sorts the list in place:

a = [3, 2, 1]
print a.sort() # in place
print a         # it's modified

Note that since a.sort() doesn't return anything, print a.sort() will print None.


Can a list original positions be retrieved after list.sort()?

No, because it modifies the original list.

How to subtract 30 days from the current datetime in mysql?

MySQL subtract days from now:

select now(), now() - interval 1 day

Prints:

2014-10-08 09:00:56     2014-10-07 09:00:56

Other Interval Temporal Expression Unit arguments:

https://dev.mysql.com/doc/refman/5.5/en/expressions.html#temporal-intervals

select now() - interval 1 microsecond 
select now() - interval 1 second 
select now() - interval 1 minute 
select now() - interval 1 hour 
select now() - interval 1 day 
select now() - interval 1 week 
select now() - interval 1 month 
select now() - interval 1 year 

Removing packages installed with go get

#!/bin/bash

goclean() {
 local pkg=$1; shift || return 1
 local ost
 local cnt
 local scr

 # Clean removes object files from package source directories (ignore error)
 go clean -i $pkg &>/dev/null

 # Set local variables
 [[ "$(uname -m)" == "x86_64" ]] \
 && ost="$(uname)";ost="${ost,,}_amd64" \
 && cnt="${pkg//[^\/]}"

 # Delete the source directory and compiled package directory(ies)
 if (("${#cnt}" == "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
 elif (("${#cnt}" > "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
 fi

 # Reload the current shell
 source ~/.bashrc
}

Usage:

# Either launch a new terminal and copy `goclean` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

goclean github.com/your-username/your-repository

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

How to download a file with Node.js (without using third-party libraries)?

You can create an HTTP GET request and pipe its response into a writable file stream:

const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
  response.pipe(file);
});

If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.

visual c++: #include files from other projects in the same solution

You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

$ENV{TZ}="GMT";
POSIX::tzset();
$time = POSIX::mktime($s,$m,$h,$d,$mo-1,$y-1900);

Show which git tag you are on?

This worked for me git describe --tags --abbrev=0

Edit 2020: As mentioned by some of the comments below, this might, or might not work for you, so be careful!

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

Why is synchronized block better than synchronized method?

It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.

Synchronized Methods

An entire method can be marked as synchronized resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.

Steps A thread access the synchronized method. It implicitly acquires the lock and execute the code. If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released.

Synchronized Blocks

To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste.

More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.

What does $(function() {} ); do?

Some Theory

$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:

$ = function() { 
        alert('I am in the $ function');
    }

JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:

window.jQuery = window.$ = jQuery;

Answer To Your Question

So what is $(function() { });?

Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.

The other way to accomplish this is like this:

$(document).ready(function() { });

As you can see this is more verbose so people prefer $(function() { })

So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.

Another way to interpret $(function() { }) is like this:

Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?

decompiling DEX into Java sourcecode

Easiest method to decompile an android app is to download an app named ShowJava from playstore . Just select the application that needs to be decompiled from the list of applications. There are three different decompiler you can use to decompile an app namely -

CFR 0.110, JaDX 0.6.1 or FernFlower (analytical decompiler) .

Among $_REQUEST, $_GET and $_POST which one is the fastest?

GET vs. POST

1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

3) $_GET is an array of variables passed to the current script via the URL parameters.

4) $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

How to embed YouTube videos in PHP?

From both long and short youtube urls you can get the embed this way:

$ytarray=explode("/", $videolink);
$ytendstring=end($ytarray);
$ytendarray=explode("?v=", $ytendstring);
$ytendstring=end($ytendarray);
$ytendarray=explode("&", $ytendstring);
$ytcode=$ytendarray[0];
echo "<iframe width=\"420\" height=\"315\" src=\"http://www.youtube.com/embed/$ytcode\" frameborder=\"0\" allowfullscreen></iframe>";

Hope it helps someone

Python : List of dict, if exists increment a dict value, if not append a new dict

Use defaultdict:

from collections import defaultdict

urls = defaultdict(int)

for url in list_of_urls:
    urls[url] += 1

How to resolve "local edit, incoming delete upon update" message

This issue often happens when we try to merge another branch changes from a wrong directory.

Ex:

Branch2\Branch1_SubDir$ svn merge -rStart:End Branch1
         ^^^^^^^^^^^^
   Merging at wrong location

A conflict that gets thrown on its execution is :

Tree conflict on 'Branch1_SubDir'
   > local missing or deleted or moved away, incoming dir edit upon merge

And when you select q to quit resolution, you get status as:

 M      .
!     C Branch1_SubDir
      >   local missing or deleted or moved away, incoming dir edit upon merge
!     C Branch1_AnotherSubDir
      >   local missing or deleted or moved away, incoming dir edit upon merge

which clearly means that the merge contains changes related to Branch1_SubDir and Branch1_AnotherSubDir, and these folders couldn't be found inside Branch1_SubDir(obviously a directory can't be inside itself).

How to avoid this issue at first place:

Branch2$ svn merge -rStart:End Branch1
 ^^^^
Merging at root location

The simplest fix for this issue that worked for me :

svn revert -R .

Error Installing Homebrew - Brew Command Not Found

try this

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"

Print <div id="printarea"></div> only?

Could you use a print stylesheet, and use CSS to arrange the content you wanted printed? Read this article for more pointers.

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

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

I was facing same issue on debian9 VM, I tried to restart MySQL but it didn't solve the issue, after that I increased the RAM (I was reduced) and it worked.

Question mark and colon in statement. What does it mean?

This is the conditional operator expression.

(condition) ? [true path] : [false path];

For example

 string value = someBooleanExpression ? "Alpha" : "Beta";

So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".

For a common pitfall that people fall into, see this question in the C# tag wiki.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Even if you have unchecked the "Display intranet sites in Compatibility View" option, and have the X-UA-Compatible in your response headers, there is another reason why your browser might default to "Compatibility View" anyways - your Group Policy. Look at your console for the following message:

HTML1203: xxx.xxx has been configured to run in Compatibility View through Group Policy.

Where xxx.xxx is the domain for your site (i.e. test.com). If you see this then the group policy for your domain is set so that any site ending in test.com will automatically render in Compatibility mode regardless of doctype, headers, etc.

For more information, please see the following link (explains the html codes): http://msdn.microsoft.com/en-us/library/ie/hh180764(v=vs.85).aspx

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

AndroidStudio: Failed to sync Install build tools

I could fix it by changing it to

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
}

in build.gradle file

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Converting JSON to XLS/CSV in Java

You could only convert a JSON array into a CSV file.

Lets say, you have a JSON like the following :

{"infile": [{"field1": 11,"field2": 12,"field3": 13},
            {"field1": 21,"field2": 22,"field3": 23},
            {"field1": 31,"field2": 32,"field3": 33}]}

Lets see the code for converting it to csv :

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON2CSV {
    public static void main(String myHelpers[]){
        String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonString);


            JSONArray docs = output.getJSONArray("infile");

            File file=new File("/tmp2/fromJSON.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }

}

Now you got the CSV generated from JSON.

It should look like this:

field1,field2,field3
11,22,33
21,22,23
31,32,33

The maven dependency was like,

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Update Dec 13, 2019:

Updating the answer, since now we can support complex JSON Arrays as well.

import java.nio.file.Files;
import java.nio.file.Paths;

import com.github.opendevl.JFlat;

public class FlattenJson {

    public static void main(String[] args) throws Exception {
        String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));

        JFlat flatMe = new JFlat(str);

        //get the 2D representation of JSON document
        flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();

        //write the 2D representation in csv format
        flatMe.write2csv("path_to_output.csv");
    }

}

dependency and docs details are in link

Strtotime() doesn't work with dd/mm/YYYY format

This workaround is simpler and more elegant than explode:

$my_date = str_replace("/", ".", $my_date);
$my_date = strtotime($my_date);
$my_date = date("Y-m-d", $my_date);

You don't have to know what format you're getting the date in, but if it comes with slashes they are replaced with full stops and it is treated as European by strtotime.

How to wrap text using CSS?

Try doing this. Works for IE8, FF3.6, Chrome

<body>
  <table>
    <tr>
      <td>
        <div style="word-wrap: break-word; width: 100px">gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div>
      </td>
    </tr>
  </table>
</body>

Synchronous XMLHttpRequest warning and <script>

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

You could fix it, setting explicitly async option of xhr request to true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

you can use this:

 var list = new SelectList(countryList, "Id", "Name");
 ViewBag.countries=list;
 @Html.DropDownList("countries",ViewBag.countries as SelectList)

How can I see if a Perl hash already has a certain key?

I guess that this code should answer your question:

use strict;
use warnings;

my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
    $hash{$key}++;
}

for my $key (keys %hash)
{
   print "$key: ", $hash{$key}, "\n";
}

Output:

three: 1
one: 1
two: 2

The iteration can be simplified to:

$hash{$_}++ for (@keys);

(See $_ in perlvar.) And you can even write something like this:

$hash{$_}++ or print "Found new value: $_.\n" for (@keys);

Which reports each key the first time it’s found.

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Custom Card Shape Flutter SDK

An Alternative Solution to the above

Card(
  shape: RoundedRectangleBorder(
     borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
  color: Colors.white,
  child: ...
)

You can use BorderRadius.only() to customize the corners you wish to manage.

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

What exactly does an #if 0 ..... #endif block do?

When the preprocessor sees #if it checks whether the next token has a non-zero value. If it does, it keeps the code around for the compiler. If it doesn't, it gets rid of that code so the compiler never sees it.

If someone says #if 0 they are effectively commenting out the code so it will never be compiled. You can think of this the same as if they had put /* ... */ around it. It's not quite the same, but it has the same effect.

If you want to understand what happened in detail, you can often look. Many compilers will allow you to see the files after the preprocessor has run. For example, on Visual C++ the switch /P command will execute the preprocessor and put the results in a .i file.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Standard: Think of it as a big standard library. When using this as a dependency you can only make libraries (.DLLs), not executables. A library made with .NET standard as a dependency can be added to a Xamarin.Android, a Xamarin.iOS, a .NET Core Windows/OS X/Linux project.

.NET Core: Think of it as the continuation of the old .NET framework, just it's opensource and some stuff is not yet implemented and others got deprecated. It extends the .NET standard with extra functions, but it only runs on desktops. When adding this as a dependency you can make runnable applications on Windows, Linux and OS X. (Although console only for now, no GUIs). So .NET Core = .NET Standard + desktop specific stuff.

Also UWP uses it and the new ASP.NET Core uses it as a dependency too.

Displaying Image in Java

Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?

How to add jQuery code into HTML Page

I would recommend to call the script like this

...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>

The js and css files must be treat differently

Put jquery as the first before other JS scripts at the bottom of <BODY> tag

  • The problem caused is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname.
  • So select 2 (two) most important scripts on your page like analytic and pixel script on the <head> tags and let the rest including the jquery to be called on the bottom <body> tag.

Put CSS style on top of <HEAD> tag after the other more priority tags

  • Moving style sheets to the document HEAD makes pages appear to be loading faster. This is because putting style sheets in the HEAD allows the page to render progressively.
  • So for css sheets, it is better to put them all on the <head> tag but let the style that shall be immediately rendered to be put in <style> tags inside <HEAD> and the rest in <body>.

You may also find other suggestion when you test your page like on Google PageSpeed Insight

PHP Convert String into Float/Double

Try using

$string = "2968789218";
$float = (double)$string;

View more than one project/solution in Visual Studio

Two ways come to mind...

  1. Open another visual studio window and open the second solution in it.

  2. It would be preferable to add your existing projects to one solution, just right click and add existing project and navigate to the project file(csproj). .... e.g. C:\Users\User\Documents\Visual Studio 2012\Projects\MySqlWindowsFormsApplication1\MySql Windows Forms Project1\MySql Windows Forms Project1.csproj ....In this second way you might want to setup multiple start up projects i.e. for people with client-server apps or apps with dependencies. ....To do this Select the solution then GoTo: Project>>Properties>>Startup Project>> Select Multiple Startup projects and set actions to Start. When you debug, the selected as start will run.

  3. For interest sake you could open another multiple solution windows to view different projects at the same time. http://www.schwammysays.net/visual-studio-2012-tip-multiple-solution-explorers/

Favicon dimensions?

Short answer

The favicon is supposed to be a set of 16x16, 32x32 and 48x48 pictures in ICO format. ICO format is different than PNG. Non-square pictures are not supported.

To generate the favicon, for many reasons explained below, I advise you to use this favicon generator. Full disclosure: I'm the author of this site.

Long, comprehensive answer

Favicon must be square. Desktop browsers and Apple iOS do not support non-square icons.

The favicon is supported by several files:

  • A favicon.ico icon.
  • Some other PNG icons.

In order to get the best results across desktop browsers (Windows/IE, MacOS/Safari, etc.), you need to combine both types of icons.

favicon.ico

Although all desktop browsers can deal with this icon, it is primarily for older version of IE.

The ICO format is different of the PNG format. This point is tricky because some browsers are smart enough to process a PNG picture correctly, even when it was wrongly renamed with an ICO extension.

An ICO file can contain several pictures and Microsoft recommends to put 16x16, 32x32 and 48x48 versions of the icon in favicon.ico. For example, IE will use the 16x16 version for the address bar, and the 32x32 for a task bar shortcut.

Declare the favicon with:

<link rel="icon" href="/path/to/icons/favicon.ico">

However, it is recommended to place favicon.ico in the root directory of the web site and to not declare it at all and let the modern browsers pick the PNG icons.

PNG icons

Modern desktop browsers (IE11, recent versions of Chrome, Firefox...) prefer to use PNG icons. The usual expected sizes are 16x16, 32x32 and "as big as possible". For example, MacOS/Safari uses the 196x196 icon if it is the biggest it can find.

What are the recommended sizes? Pick your favorite platforms:

The PNG icons are declared with:

<link rel="icon" type="image/png" href="/path/to/icons/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-32x32.png" sizes="32x32">
...

Beware: Firefox does not support the sizes attribute and uses the last PNG icon it finds. Make sure to declare the 32x32 picture last: it is good enough for Firefox, and that will prevent it from downloading a big picture it does not need. edit: fixed in 2016.

Also note that Chrome does not support the sizes attribute and tends to load all declared icons. Better not declare too many icons. edit: fixed in 2018.

Mobile platforms

This question is about desktop favicon so there is no need to delve too much in this topic.

Apple defines touch icon for the iOS platform. iOS does not support non-square icon. It simply rescales non-square pictures to make them square (look for the Kioskea example).

Android Chrome relies on the Apple touch icon and also defines a 192x192 PNG icon.

Microsoft defines the tile picture and the browserconfig.xml file.

Conclusion

Generating a favicon that works everywhere is quite complex. I advise you to use this favicon generator. Full disclosure: I'm the author of this site.

Android – Listen For Incoming SMS Messages

If someone referring how to do the same feature (reading OTP using received SMS) on Xamarin Android like me :

  1. Add this code to your AndroidManifest.xml file :

    <receiver android:name=".listener.BroadcastReveiverOTP">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
    </receiver>
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.BROADCAST_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    
  2. Then create your BroadcastReveiver class in your Android Project.

    [BroadcastReceiver(Enabled = true)] [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)] 
    public class BroadcastReveiverOTP : BroadcastReceiver {
            public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    
            protected string message, address = string.Empty;
    
            public override void OnReceive(Context context, Intent intent)
            {
                if (intent.HasExtra("pdus"))
                {
                    var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
                    foreach (var item in smsArray)
                    {
                        var sms = SmsMessage.CreateFromPdu((byte[])item);
                        address = sms.OriginatingAddress;
                        if (address.Equals("NotifyDEMO"))
                        {
                            message = sms.MessageBody;
                            string[] pin = message.Split(' ');
                            if (!string.IsNullOrWhiteSpace(pin[0]))
                            { 
                                    // NOTE : Here I'm passing received OTP to Portable Project using MessagingCenter. So I can display the OTP in the relevant entry field.
                                    MessagingCenter.Send<object, string>(this,MessengerKeys.OnBroadcastReceived, pin[0]);
                            }
                            }
                    }
                }
            }
    }
    
  3. Register this BroadcastReceiver class in your MainActivity class on Android Project:

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
    
            // Initialize your class
            private BroadcastReveiverOTP _receiver = new BroadcastReveiverOTP ();
    
            protected override void OnCreate(Bundle bundle) { 
                    base.OnCreate(bundle);
    
                    global::Xamarin.Forms.Forms.Init(this, bundle);
                    LoadApplication(new App());
    
                    // Register your receiver :  RegisterReceiver(_receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
    
            }
    }
    

How do I list / export private keys from a keystore?

A portion of code originally from Example Depot for listing all of the aliases in a key store:

    // Load input stream into keystore
    keystore.load(is, password.toCharArray());

    // List the aliases
    Enumeration aliases = keystore.aliases();
    for (; aliases.hasMoreElements(); ) {
        String alias = (String)aliases.nextElement();

        // Does alias refer to a private key?
        boolean b = keystore.isKeyEntry(alias);

        // Does alias refer to a trusted certificate?
        b = keystore.isCertificateEntry(alias);
    }

The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app.

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        String b64 = new BASE64Encoder().encode(key.getEncoded());
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

Note: this use Sun package, which is a "bad thing".
If you can download apache commons code, here is a version which will compile without warning:

javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java

and will give the same result:

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        //String b64 = new BASE64Encoder().encode(key.getEncoded());
        String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

You can use it like so:

java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat

How to throw RuntimeException ("cannot find symbol")

using new keyword we always create a instance (new object) and throwing it , not called a method

throw new RuntimeException("Your Message");

You need the new in there. It's creating an instance and throwing it, not calling a method.

int no= new Scanner().nextInt();   // we crate an instance using new keyword and throwing it 

using new keyword memory clean [because use and throw]

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..
    }
}, 1000);

What do two question marks together mean in C#?

enter image description here

The two question marks (??) indicate that its a Coalescing operator.

Coalescing operator returns the first NON-NULL value from a chain. You can see this youtube video which demonstrates the whole thing practically.

But let me add more to what the video says.

If you see the English meaning of coalescing it says “consolidate together”. For example below is a simple coalescing code which chains four strings.

So if str1 is null it will try str2, if str2 is null it will try str3 and so on until it finds a string with a non-null value.

string final = str1 ?? str2 ?? str3 ?? str4;

In simple words Coalescing operator returns the first NON-NULL value from a chain.

SQL: Return "true" if list of records exists?

Assuming you're using SQL Server, the boolean type doesn't exist, but the bit type does, which can hold only 0 or 1 where 0 represents False, and 1 represents True.

I would go this way:

select 1
    from Products
    where ProductId IN (1, 10, 100)

Here, a null or no row will be returned (if no row exists).

Or even:

select case when EXISTS (
    select 1
        from Products
        where ProductId IN (1, 10, 100)
    ) then 1 else 0 end as [ProductExists]

Here, either of the scalar values 1 or 0 will always be returned (if no row exists).

How to sort an ArrayList?

For your example, this will do the magic in Java 8

List<Double> testList = new ArrayList();
testList.sort(Comparator.naturalOrder());

But if you want to sort by some of the fields of the object you are sorting, you can do it easily by:

testList.sort(Comparator.comparing(ClassName::getFieldName));

or

 testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());

or

 testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());

Sources: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

Deleting an object in java?

You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).

Example 1:

Object a = new Object();
a = null; // after this, if there is no reference to the object,
          // it will be deleted by the garbage collector

Example 2:

if (something) {
    Object o = new Object(); 
} // as you leave the block, the reference is deleted.
  // Later on, the garbage collector will delete the object itself.

Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Uncommon but may help some.

ensure you're using [HttpPut] from System.Web.Http

We were getting a 'Method not allowed' 405, on a HttpPut decorrated method.

Our problem would seem to be uncommon, as we accidentally used the [HttpPut] attribute from System.Web.Mvc and not System.Web.Http

The reason being, resharper suggested the .Mvc version, where-as usually System.Web.Http is already referenced when you derive directly from ApiController we were using a class that extended ApiController.

Using multiprocessing.Process with a maximum number of simultaneous processes

more generally, this could also look like this:

import multiprocessing
def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

numberOfThreads = 4


if __name__ == '__main__':
    jobs = []
    for i, param in enumerate(params):
        p = multiprocessing.Process(target=f, args=(i,param))
        jobs.append(p)
    for i in chunks(jobs,numberOfThreads):
        for j in i:
            j.start()
        for j in i:
            j.join()

Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.

When to use single quotes, double quotes, and backticks in MySQL

SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').

Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.

If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:

let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';

If ther's a where statement in your query and/or trying to insert a value and/or an update of value which is string use single quote(') for these values like:

let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";

//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error

let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';

//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.

If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:

let query = 'select is, name from accounts where name = \'John\'';

Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:

let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith

//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";

//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';

If need further clearance do follow quotes in JavaScript

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info: