doseofdev
doseofdev
Dose of Dev
20 posts
Don't wanna be here? Send us removal request.
doseofdev · 9 years ago
Text
How Calendar class’s add and roll methods affect different date parts
In Java, Calendar class’s add() method, with a positive argument, moves the specified date part to future, may move the "bigger" date parts to future, and may move the "smaller" date parts to past.
For example, considering that 2016 is a leap year:
Calendar c = Calendar.getInstance(); c.set(2015, 11, 31, 0, 0, 0); System.out.println(c.getTime()); //Thu Dec 31 00:00:00 CST 2015 c.add(Calendar.MONTH, 2); System.out.println(c.getTime()); //Mon Feb 29 00:00:00 CST 2016
Calendar class’s roll() method, with a positive argument, moves the specified date part to future, does not change the "bigger" date parts, and may move the "smaller" date parts to past.
For example:
Calendar c = Calendar.getInstance(); c.set(2015, 11, 31, 0, 0, 0); System.out.println(c.getTime()); //Thu Dec 31 00:00:00 CST 2015 c.roll(Calendar.MONTH, 2); System.out.println(c.getTime()); //Sat Feb 28 00:00:00 CST 2015
0 notes
doseofdev · 9 years ago
Text
The difference between “parse” methods in NumberFormat and wrapper classes
In Java, method NumberFormat.parse() receives a string and parses it from the beginning to produce a number. But the method may not use the entire text of the given string, and it does not throw an exception if it can parse the beginning of the string. For example:
try {  System.out.println(NumberFormat.getInstance().parse("123xyz")); //123 } catch (ParseException e) {  e.printStackTrace(); }
Note that the “parse” methods of wrapper classes, Integer.parseInt() for example, behave differently. Although you do not need to enclose the call inside a try/catch block, it throws a NumberFormatException if it cannot parse the entire string:
System.out.println(Integer.parseInt("123xyz")); //Exception in thread "main" java.lang.NumberFormatException: For input string: "123xyz"
0 notes
doseofdev · 9 years ago
Text
Passing wrong argument when instantiating a StringBuffer or StringBuilder
In Java, make sure you do not instantiate StringBuffer or StringBuilder with a char argument by mistake. These classes have a constructor that gets an int argument which constructs the object with no characters in it but with the specified initial capacity. So if you pass a char argument, this constructor is used rather than StringBuffer(String str) or StringBuilder(String str) which you probably intended to use. 
For example the following code:
StringBuffer sb = new StringBuffer('a'); System.out.println("sb.toString() is '" + sb.toString() + "'"); System.out.println("sb.length() is " + sb.length()); System.out.println("sb.capacity() is " + sb.capacity());
Produces this output:
sb.toString() is '' sb.length() is 0 sb.capacity() is 97
0 notes
doseofdev · 9 years ago
Text
Use setInterval() function to execute a code repeatedly with fixed time delay
In JavaScript you can use the setInterval() function in order to call a function or execute a code snippet repeatedly with a fixed time delay between each call. For example the following code logs ‘test’ every one second:
setInterval(myLogFunction, 1000); function myLogFunction() {   console.log("test"); }
You can also execute a code snippet, although not recommended because of security and performance:
setInterval('console.log("test")', 1000);
0 notes
doseofdev · 9 years ago
Text
Search for multiple strings using bash commands
Use bash commands awk or sed to search for multiple strings when you want all to be part of your search criteria. For example given these three files:
$ ls Test1.txt Test2.txt Test3.txt $ cat Test1.txt one two three $ cat Test2.txt one two $ cat Test3.txt one three
The following commands search for strings ‘one’ AND ’two’ in ANY order:
$ awk '/two/ && /one/' * one two three one two $ sed '/two/!d; /one/!d' * one two three one two
0 notes
doseofdev · 9 years ago
Text
Implicit modifiers for interface methods in Java
In Java, interface methods are implicitly public abstract, although using these modifiers explicitly does not cause compiler error:
public interface InterfaceA {   public abstract void method1();     //explicitly public abstract   void method2();                     //implicitly public abstract   abstract void method3();            //implicitly public   public void method4();              //implicitly abstract   private void method5();             //compile error!   protected void method6();           //compile error!   final void method7();               //compile error! }
Note that the class that implements an interface method, must declare it public, otherwise it violates the overriding rule regarding access modifier:
public class TestA implements InterfaceA {   public void method1() {}            //correct   void method2() {}                   //compile error!   protected void method3() {}         //compile error!   private void method4() {}           //compile error! }
0 notes
doseofdev · 9 years ago
Text
Prevent flash display of {{}} in an Angular page
When you use an Angular expression in a page (specially the index page) it is possible that the page is loaded before Angular compiles the expression. This causes a brief display of the raw expression like {{my-expression}}. To avoid this, use ng-bind instead.
For example instead of using expression {{model.value}} in the following div:
 <div>      <input type="text" ng-model="model.value"/>      <pre>value=<span>{{model.value}}</span></pre>  </div>
use ng-bind:
 <div>      <input type="text" ng-model="model.value"/>      <pre>value=<span ng-bind="model.value"></span></pre>  </div>
Another solution is to use ng-cloak on body tag and the following CSS:
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {      display: none !important; }
0 notes
doseofdev · 11 years ago
Text
Accessing an object's hidden property [[Prototype]] in JavaScript
In JavaScript, each object has a hidden property [[Prototype]] which represents the original prototype property of its constructor. There are several ways to access this property. For example for the following objects:
var a = new Array(); var n = new Number(); var f = function myFunction(){};
1) Using Object.getPrototypeOf() method:
Object.getPrototypeOf(a)          //"[]" Object.getPrototypeOf(n)          //"Number {}" Object.getPrototypeOf(f)          //"function Empty() {}"
2) Using the object's constructor property:
a.constructor.prototype          //"[]" n.constructor.prototype          //"Number {}" f.constructor.prototype          //"function Empty() {}"
3) Using the object's __proto__ property (This property is deprecated and should not be used):
a.__proto__          //"[]" n.__proto__          //"Number {}" f.__proto__          //"function Empty() {}"
0 notes
doseofdev · 11 years ago
Text
Adding Objects of Different Types to Java Collections
In Java, adding objects of different non-comparable types to an ordered collection like TreeSet passes the compiler test but throws ClassCastException at runtime. For example, the following throws the runtime exception on third line:
Set set = new TreeSet(); set.add("2"); set.add(3);
The reason is that it cannot compare String "2" and Integer 3 objects to keep the TreeSet in order. If set was an unordered collection, like HashSet, no runtime exception would be thrown.
0 notes
doseofdev · 11 years ago
Text
Use Immediately-Invoked Function Expression For Access Control In JavaScript
In JavaScript, you can define an Immediately-Invoked Function Expression (IIFE) to control accessing public and private properties. You do this by declaring a variable as a function expression and executing it right there. The function returns an object containing public variables and functions only. Here is an example:
var myPublicVar = (function() {    var myInnerPublicVar = "A",    myInnerPrivateVar = "a",    myInnerPublicFunction = function() {return myInnerPrivateVar;};    return {       myInnerPublicVar : myInnerPublicVar,         myInnerPublicFunction : myInnerPublicFunction    }; }()); console.log(window.myPublicVar.myInnerPublicVar);           //"A" console.log(window.myPublicVar.myInnerPublicFunction());    //"a" console.log(window.myPublicVar.myInnerPrivateVar);          //undefined
0 notes
doseofdev · 11 years ago
Text
Resume With Pauses Blocked In Chrome Developer Tools
When using debugger in Chrome Developer Tools, you can click and hold the "Resume script execution" button to see the option to "Resume with all pauses blocked for 500 ms". This is handy when your breakpoint is inside a loop.
0 notes
doseofdev · 11 years ago
Text
Using method setMaximumFractionDigits() in Java
In Java, setting maximum number of fractional digits using NumberFormat.setMaximumFractionDigits() only applies to formatting. It is ignored when parsing. Here is an example:
NumberFormat nf = NumberFormat.getInstance(); System.out.println(nf.format(0.123456));    //0.123 nf.setMaximumFractionDigits(4); System.out.println(nf.format(0.123456));    //0.1235 System.out.println(nf.parse("0.123456"));   //0.123456
0 notes
doseofdev · 11 years ago
Text
Using "viewport" Meta Tag to Optimize HTML Pages For Mobile Devices
Use viewport meta tag to control the HTML page's width and scale for smaller displays. Setting content to "width=device-width" fits the page to the width of the screen, and setting user-scalable to "no" prevents the user to change the scale by zooming. This will make your page look more like a native app:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
0 notes
doseofdev · 11 years ago
Text
Using console.table() to Log Data In Tabular Format
In Chrome Developer Tools, you can use console.table() to log data in tabular format. Almost everyone knows about and uses console.log(), but console.table() can also be used to log contents of an array of objects, or a two dimensional array, in a nicely formatted table. Here are some examples:
Tumblr media
0 notes
doseofdev · 11 years ago
Text
Sorting Array of Numbers in JavaScript
In JavaScript, the sort() method by default sorts an array in alphabetical order. For array of numbers, this could lead to unwanted result. For example, the following will result in array [1, 13, 2]:
[2, 13, 1].sort();
In order to sort array of numbers correctly, you must pass a function to the sort() method as argument to define how elements are sorted. The function receives two arguments and returns a positive, zero, or negative value to indicate that when comparing two elements, the first one is greater than, equal to, or less than the second one. For example, the following will sort the numbers in ascending order:
[2, 13, 1].sort(function(a, b) { return a - b; });
and this will sort them in descending order:
[2, 13, 1].sort(function(a, b) { return b - a; });
0 notes
doseofdev · 11 years ago
Text
Sending and Receiving Extra Information Using Intents in Android
In Android, you can send extra information to an Activity using an Intent object's putExtra() method. For example, if you are opening an Activity with an Intent to compose an email and want to pass the email address:
intent.putExtra("email", "[email protected]");
And at the other end, in the Activity that receives the Intent, you can get the extra information using getExtras().getXxx() or getXxxExtra() methods (the first one lets you define an optional default value), where Xxx is a data type like String, Double, Boolean...:
intent.getExtras().getString("email", "[email protected]"); intent.getStringExtra("email");
0 notes
doseofdev · 11 years ago
Text
Representing Even or Odd Elements in CSS3
In CSS3, you can use the nth-child() pseudo-class to represent even or odd elements. For example the following CSS sets the background color to gray for all even rows in the HTML table:
tr:nth-child(2n) {    background-color: #c0c0c0; }
You can use nth-child(2n + 1) to represent odd elements.
The argument to the nth-child() pseudo-class can be in (an + b) format where a and b are integers. For example nth-child(3n + 2) represents 2nd, 5th, 8th... elements.
0 notes