Programs & Examples On #Device instance id

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Javascript dynamic array of strings

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).


var myCars=new Array();

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);


var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:


will result in the following output:


Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:


Now, the following code line:


will result in the following output:


Chrome Fullscreen API

Here are some functions I created for working with fullscreen in the browser.

They provide both enter/exit fullscreen across most major browsers.

function isFullScreen()
    return (document.fullScreenElement && document.fullScreenElement !== null)
         || document.mozFullScreen
         || document.webkitIsFullScreen;

function requestFullScreen(element)
    if (element.requestFullscreen)
    else if (element.msRequestFullscreen)
    else if (element.mozRequestFullScreen)
    else if (element.webkitRequestFullscreen)

function exitFullScreen()
    if (document.exitFullscreen)
    else if (document.msExitFullscreen)
    else if (document.mozCancelFullScreen)
    else if (document.webkitExitFullscreen)

function toggleFullScreen(element)
    if (isFullScreen())
        requestFullScreen(element || document.documentElement);

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :


GRANT  USAGE   ON SCHEMA public  TO user;

GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Background Image for Select (dropdown) does not work in Chrome

you can use the below css styles for all browsers except Firefox 30

select {
  background: url(dropdown_arw.png) no-repeat right center;
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  width: 90px;
  text-indent: 0.01px;
  text-overflow: "";

demo page -


here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb precise main" | tee -a /etc/apt/sources.list
echo "deb-src precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp:// --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How Should I Set Default Python Version In Windows?

This worked for me:

Go to

Control Panel\System and Security\System


Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn't exist)


and set


or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table

Uninstall Eclipse under OSX?

I just had a similar problem, with the GWT-PlugIn not showing up in the interface. Deleting the eclipse folder did not solve it, GWT was still there! Deleting workspace didn't work! But deleting the .eclipse folder in the home directory did! I'm working under WIndows 7 here, but it should be the same with OSX. But you may have to make the folder visible first. Under linux based system, folders starting with a dot are invisible by default.

This folder was probably the reason I had problems in the first place. If I remember right, I switched from basic Eclipse to EE, but didn't delete this folder.

In my opinion, an uninstall skript would do Eclipse quite good.

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).



   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'

   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:



This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Checking whether a String contains a number value in Java

      return true;
}catch (Exception  e){
      return false;

or you can do it himself:

 for ( int i = 0; i < string.length; ++i ) {
      if ( !( string[i] >= '0' || string[i] <= '9' ) )
           return false;
 return true;

Of course is also function isDigit

Java Delegates?

While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.

Why isn't Python very good for functional programming?

One thing that is really important for this question (and the answers) is the following: What the hell is functional programming, and what are the most important properties of it. I'll try to give my view of it:

Functional programming is a lot like writing math on a whiteboard. When you write equations on a whiteboard, you do not think about an execution order. There is (typically) no mutation. You don't come back the day after and look at it, and when you make the calculations again, you get a different result (or you may, if you've had some fresh coffee :)). Basically, what is on the board is there, and the answer was already there when you started writing things down, you just haven't realized what it is yet.

Functional programming is a lot like that; you don't change things, you just evaluate the equation (or in this case, "program") and figure out what the answer is. The program is still there, unmodified. The same with the data.

I would rank the following as the most important features of functional programming: a) referential transparency - if you evaluate the same statement at some other time and place, but with the same variable values, it will still mean the same. b) no side effect - no matter how long you stare at the whiteboard, the equation another guy is looking at at another whiteboard won't accidentally change. c) functions are values too. which can be passed around and applied with, or to, other variables. d) function composition, you can do h=g·f and thus define a new function h(..) which is equivalent to calling g(f(..)).

This list is in my prioritized order, so referential transparency is the most important, followed by no side effects.

Now, if you go through python and check how well the language and libraries supports, and guarantees, these aspects - then you are well on the way to answer your own question.

How do I pull from a Git repository through an HTTP proxy?

It looks like you're using a mingw compile of Git on windows (or possibly another one I haven't heard about). There are ways to debug this: I believe all of the http proxy work for git is done by curl. Set this environment variable before running git:


This should at least give you an idea of what is going on behind the scenes.

Passing multiple variables to another page in url

You are checking isset($_GET['event_id'] but you've not set that get variable in your hyperlink, you are just adding email

http://localhost/main.php?email=" . $email_address . $event_id

And add another GET variable in your link

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

You did not use to concatenate your string if you are using " quotes

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

Where to get "UTF-8" string literal in Java?

Class org.apache.commons.lang3.CharEncoding.UTF_8 is deprecated after Java 7 introduced java.nio.charset.StandardCharsets

  • @see JRE character encoding names
  • @since 2.1
  • @deprecated Java 7 introduced {@link java.nio.charset.StandardCharsets}, which defines these constants as
  • {@link Charset} objects. Use {@link Charset#name()} to get the string values provided in this class.
  • This class will be removed in a future release.

How to use "like" and "not like" in SQL MSAccess for the same field?

What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.

I tested these on MS Access 2010 and are all valid:

  1. Like "BB"

  2. (Like "BB")

  3. (Not Like "BB")

How do I convert a decimal to an int in C#?

decimal d = 5.5;

int i = decimal.ToInt32(d);// you will get i = 5

ref: link text

How to calculate distance from Wifi router using Signal Strength?

FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.

FSPL (dB) = 20log10(d) + 20log10(f) + K

d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:

FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44

From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.

Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin

With the above two Free Space Path Loss equations, we can find out the Distance in km.

Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20

The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.


d = distance [km]
f = frequency [GHz]
r = radius [m]

Source :

javascript popup alert on link click

just make it function,

<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)

<a href="javascript:AlertIt();">click me</a>

Can someone explain how to implement the jQuery File Upload plugin?

You can use uploadify this is the best multiupload jquery plugin i have used.

The implementation is easy, the browser support is perfect.

Parallel foreach with asynchronous lambda

I've created an extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
        if (maxDegreeOfParallelism.HasValue)
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                        await action(item).ContinueWith(res =>
                            // action is completed, so decrement the number of currently running tasks

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            await Task.WhenAll(enumerable.Select(item => action(item)));

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
        await SomeAsyncMethod(item);

How to check if anonymous object has a method?

What do you mean by an "anonymous object?" myObj is not anonymous since you've assigned an object literal to a variable. You can just test this:

if (typeof myObj.prop2 === 'function')
    // do whatever

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:


that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.


Preventing form resubmission

The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:


In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)

How can I get sin, cos, and tan to use degrees instead of radians?

I like a more general functional approach:

* converts a trig function taking radians to degrees
* @param {function} trigFunc - eg. Math.cos, Math.sin, etc.
* @param {number} angle - in degrees
* @returns {number}
const dTrig = (trigFunc, angle) => trigFunc(angle * Math.PI / 180);


function dTrig(trigFunc, angle) {
  return trigFunc(angle * Math.PI / 180);

which can be used with any radian-taking function:

dTrig(Math.sin, 90);
  // -> 1

dTrig(Math.tan, 180);
  // -> 0

Hope this helps!

Why does the 260 character path length limit exist in Windows?

Quoting this article

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

Why doesn't Java offer operator overloading?

Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.

At least I think that's the reason. I'm on your side anyway. :)

Print Combining Strings and Numbers

In Python 3.6

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

What is the difference between a string and a byte string?

The Python languages includes str and bytes as standard "Built-in Types". In other words, they are both classes. I don't think it's worthwhile trying to rationalize why Python has been implemented this way.

Having said that, str and bytes are very similar to one another. Both share most of the same methods. The following methods are unique to the str class:


The following methods are unique to the bytes class:


html cellpadding the left side of a cell

I recently had to do this to create half decent looking emails for an email client that did not support the CSS necessary. For an HTML only solution I use a wrapping table to provide the padding.

<table border="1" cellspacing="0" cellpadding="0">_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_
        <td width="5"></td>_x000D_
            This cells padding matches what you want._x000D_
                <li>5px Left, Top, Bottom padding</li>_x000D_
                <li>10px on the right</li>_x000D_
            </ul>    _x000D_
            You can then put your table inside this_x000D_
            cell with no spacing or padding set.                    _x000D_
        <td width="10"></td>_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_

As of 2017 you would only do this for old email client support, it's pretty overkill.

How to print Boolean flag in NSLog?

NSArray *array1 = [NSArray arrayWithObjects:@"todd1", @"todd2", @"todd3", nil];
bool objectMembership = [array1 containsObject:@"todd1"];
NSLog(@"%d",objectMembership);  // prints 1 or 0

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

jquery to validate phone number

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Supports :

  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

How to fix Broken pipe?

SocketException: Broken pipe, is caused by the 'other end' (The client or the server) closing the connection while your code is either reading from or writing to the connection.

This is a very common exception in client/server applications that receive traffic from clients or servers outside of the application control. For example, the client is a browser. If the browser makes an Ajax call, and/or the user simply closes the page or browser, then this can effectively kill all communication unexpectedly. Basically, you will see this error any time the other end terminates their application, and you were not anticipating it.

If you experience this Exception in your application, then it means you should check your code where the IO (Input/Output) occurs and wrap it with a try/catch block to catch this IOException. It is then, up to you to decide how you want to handle this semi-valid situation.

In your case, the earliest place where you still have control is the call to HttpMethodDirector.executeWithRetry - So ensure that call is wrapped with the try/catch block, and handle it how you see fit.

I would strongly advise against logging SocketException-Broken Pipe specific errors at anything other than debug/trace levels. Else, this can be used as a form of DOS (Denial Of Service) attack by filling up the logs. Try and harden and negative-test your application for this common scenario.

SQL Row_Number() function in Where Clause

I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  10. ORDER BY
  11. TOP

I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE is always processed before SELECT making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.

Why is document.write considered a "bad practice"?

Based on analysis done by Google-Chrome Dev Tools' Lighthouse Audit,

For users on slow connections, external scripts dynamically injected via document.write() can delay page load by tens of seconds.

enter image description here

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo:

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:


Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

For those who are using this format all the timme like me I did an extension method. I just wanted to share because I think it can be usefull to you.

     /// <summary>
    /// Convert a date to a human readable ISO datetime format. ie. 2012-12-12 23:01:12
    /// this method must be put in a static class. This will appear as an available function
    /// on every datetime objects if your static class namespace is declared.
    /// </summary>
    public static string ToIsoReadable(this DateTime dateTime)
        return dateTime.ToString("yyyy-MM-dd HH':'mm':'ss");

Something better than .NET Reflector?

9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...

There is also a new one (at least for me) named Dis#.

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

After installing OpenSSL I was required to create a new environment variable:

  • Value: C:\Program Files\OpenSSL\openssl.cnf

In powershell:

$env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL\openssl.cnf"

This value differs from previous installation versions (as seen in a previous edit of this post). Also, don't forget to add the openssl binary folder ${env:ProgramFiles}\OpenSSL to your Path.

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute


$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Convert xlsx to csv in Linux with command line

If you already have a Desktop environment then I'm sure Gnumeric / LibreOffice would work well, but on a headless server (such as Amazon Web Services), they require dozens of dependencies that you also need to install.

I found this Python alternative:

$ easy_install xlsx2csv
$ xlsx2csv file.xlsx > newfile.csv

Took 2 seconds to install and works like a charm.

If you have multiple sheets you can export all at once, or one at a time:

$ xlsx2csv file.xlsx --all > all.csv
$ xlsx2csv file.xlsx --all -p '' > all-no-delimiter.csv
$ xlsx2csv file.xlsx -s 1 > sheet1.csv

He also links to several alternatives built in Bash, Python, Ruby, and Java.

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

Unit Testing: DateTime.Now


public void TestOfDateTime()  
      var firstValue = DateTime.Now;
      MDateTime.NowGet = () => new DateTime(2000,1,1);
      var secondValue = DateTime.Now;
      Assert(firstValue > secondValue); // would be false if 'moleing' failed

Disclaimer - I work on Moles

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];




  return classElements;


Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

Setting SMTP details for php mail () function

Check out your php.ini, you can set these values there.

Here's the description in the php manual:

If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer

Map implementation with duplicate keys

what about such a MultiMap impl?

public class MultiMap<K, V> extends HashMap<K, Set<V>> {
  private static final long serialVersionUID = 1L;
  private Map<K, Set<V>> innerMap = new HashMap<>();

  public Set<V> put(K key, V value) {
    Set<V> valuesOld = this.innerMap.get(key);
    HashSet<V> valuesNewTotal = new HashSet<>();
    if (valuesOld != null) {
    this.innerMap.put(key, valuesNewTotal);
    return valuesOld;

  public void putAll(K key, Set<V> values) {
    for (V value : values) {
      put(key, value);

  public Set<V> put(K key, Set<V> value) {
    Set<V> valuesOld = this.innerMap.get(key);
    putAll(key, value);
    return valuesOld;

  public void putAll(Map<? extends K, ? extends Set<V>> mapOfValues) {
    for (Map.Entry<? extends K, ? extends Set<V>> valueEntry : mapOfValues.entrySet()) {
      K key = valueEntry.getKey();
      Set<V> value = valueEntry.getValue();
      putAll(key, value);

  public Set<V> putIfAbsent(K key, Set<V> value) {
    Set<V> valueOld = this.innerMap.get(key);
    if (valueOld == null) {
      putAll(key, value);
    return valueOld;

  public Set<V> get(Object key) {
    return this.innerMap.get(key);

  etc. etc. override all public methods size(), clear() .....


Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> import pickle
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info:

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];

//map[myKey1] == get(myKey1);

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.

Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.


PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

 * Centers a string of text in a terminal window
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 * @return string The padded result, ready to echo
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";

echo center('foo');
echo center('bar baz', '=');

This application has no explicit mapping for /error

I've been getting a similar error while trying out a Spring Boot sample application with Thymeleaf, tried all the different solutions provided unfortunately didn't worked.

My error was that the returned string from Controller method was not having a respective view html.

It might be you have missed or there could be some typo in the file name. As shown in the example inside the controller

public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService.loadAll().map(
            path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                    "serveFile", path.getFileName().toString()).build().toString())

    return "uploadForm";

the return String should be match the html file name at


Thymeleaf will look for the file with same name as in the return type and display the view. You can try with any html file and give the file name in return statement and it will populate the respective view.

PHP Using RegEx to get substring of a string

$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string

Arrays.fill with multidimensional array in Java

This is because a double[][] is an array of double[] which you can't assign 0.0 to (it would be like doing double[] vector = 0.0). In fact, Java has no true multidimensional arrays.

As it happens, 0.0 is the default value for doubles in Java, thus the matrix will actually already be filled with zeros when you get it from new. However, if you wanted to fill it with, say, 1.0 you could do the following:

I don't believe the API provides a method to solve this without using a loop. It's simple enough however to do it with a for-each loop.

double[][] matrix = new double[20][4];

// Fill each row with 1.0
for (double[] row: matrix)
    Arrays.fill(row, 1.0);

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How to get the unique ID of an object which overrides hashCode()?

// looking for that last hex?

If you're looking into the hashcode Java types when you do a .toString() on an object the underlying code is this:


opening a window form from another form programmatically

To open from with button click please add the following code in the button event handler

var m = new Form1();

Here Form1 is the name of the form which you want to open.

Also to close the current form, you may use


Function for 'does matrix contain value X?'

If you need to check whether the elements of one vector are in another, the best solution is ismember as mentioned in the other answers.

ismember([15 17],primes(20))

However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf

It gives a very practical example:

[tf, loc]=ismember(0.3, 0:0.1:1) % returns false 
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true

Though the default tolerance should normally be sufficient, it gives you more flexibility

ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true

Redirect From Action Filter Attribute

Set filterContext.Result

With the route name:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

You can also do something like:

filterContext.Result = new ViewResult
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData

If you want to use RedirectToAction:

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
    return base.RedirectToAction(action, controller);

Then your filter would look something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");

What happens if you don't commit a transaction to a database (say, SQL Server)?

Example for Transaction

begin tran tt

Your sql statements

if error occurred rollback tran tt else commit tran tt

As long as you have not executed commit tran tt , data will not be changed

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I had the same issue running it in my pipeline.

For me, the issue was that I was using node version v10.0.0 in my docker container.

Updating it to v14.7.0 solved it for me

Install a .NET windows service without InstallUtil.exe

Take a look at the InstallHelper method of the ManagedInstaller class. You can install a service using:

string[] args;

This is exactly what InstallUtil does. The arguments are the same as for InstallUtil.

The benefits of this method are that it involves no messing in the registry, and it uses the same mechanism as InstallUtil.

Example of a strong and weak entity types

First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.

A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.

For more info Refer :

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.

Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

Maven: mvn command not found

I tried solutions from other threads. Adding M2 and M2_HOME at System variables, and even at User variables. Running cmd as admin. None of the methods worked.

But today I added entire path to maven bin to my System variables "PATH" (C:\Program Files (x86)\Apache Software Foundation\apache-maven-3.1.0\bin) besides other paths, and so far it's working good. Hopefully it'll stay that way.

HTML form with side by side input fields

Put style="float:left" on each of your divs:

<div style="float:left;">...........


<div style="float:left;">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />

<div style="float:left;">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />

To put an element on new line, put this div below it:

<div style="clear:both;">&nbsp;</div>

Of course, you can also create classes in the CSS file:



And then your html should look like this:

<div class="left">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />

<div class="left">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />

To put an element on new line, put this div below it:

<div class="clear">&nbsp;</div>

More Info:

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))

Can I do Model->where('id', ARRAY) multiple where conditions?

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', '[email protected]')
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

How to convert uint8 Array to base64 Encoded String?

All solutions already proposed have severe problems. Some solutions fail to work on large arrays, some provide wrong output, some throw an error on btoa call if an intermediate string contains multibyte characters, some consume more memory than needed.

So I implemented a direct conversion function which just works regardless of the input. It converts about 5 million bytes per second on my machine.

MIT License_x000D_
Copyright (c) 2020 Egor Nepomnyaschih_x000D_
Permission is hereby granted, free of charge, to any person obtaining a copy_x000D_
of this software and associated documentation files (the "Software"), to deal_x000D_
in the Software without restriction, including without limitation the rights_x000D_
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell_x000D_
copies of the Software, and to permit persons to whom the Software is_x000D_
furnished to do so, subject to the following conditions:_x000D_
The above copyright notice and this permission notice shall be included in all_x000D_
copies or substantial portions of the Software._x000D_
// This constant can also be computed with the following algorithm:_x000D_
const base64abc = [],_x000D_
 A = "A".charCodeAt(0),_x000D_
 a = "a".charCodeAt(0),_x000D_
 n = "0".charCodeAt(0);_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
 base64abc.push(String.fromCharCode(A + i));_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
 base64abc.push(String.fromCharCode(a + i));_x000D_
for (let i = 0; i < 10; ++i) {_x000D_
 base64abc.push(String.fromCharCode(n + i));_x000D_
const base64abc = [_x000D_
 "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",_x000D_
 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",_x000D_
 "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",_x000D_
 "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",_x000D_
 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"_x000D_
// This constant can also be computed with the following algorithm:_x000D_
const l = 256, base64codes = new Uint8Array(l);_x000D_
for (let i = 0; i < l; ++i) {_x000D_
 base64codes[i] = 255; // invalid character_x000D_
base64abc.forEach((char, index) => {_x000D_
 base64codes[char.charCodeAt(0)] = index;_x000D_
base64codes["=".charCodeAt(0)] = 0; // ignored anyway, so we just need to prevent an error_x000D_
const base64codes = [_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,_x000D_
 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255,_x000D_
 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,_x000D_
 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,_x000D_
 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,_x000D_
 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51_x000D_
function getBase64Code(charCode) {_x000D_
 if (charCode >= base64codes.length) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 const code = base64codes[charCode];_x000D_
 if (code === 255) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 return code;_x000D_
export function bytesToBase64(bytes) {_x000D_
 let result = '', i, l = bytes.length;_x000D_
 for (i = 2; i < l; i += 3) {_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
  result += base64abc[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)];_x000D_
  result += base64abc[bytes[i] & 0x3F];_x000D_
 if (i === l + 1) { // 1 octet yet to write_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[(bytes[i - 2] & 0x03) << 4];_x000D_
  result += "==";_x000D_
 if (i === l) { // 2 octets yet to write_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
  result += base64abc[(bytes[i - 1] & 0x0F) << 2];_x000D_
  result += "=";_x000D_
 return result;_x000D_
export function base64ToBytes(str) {_x000D_
 if (str.length % 4 !== 0) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 const index = str.indexOf("=");_x000D_
 if (index !== -1 && index < str.length - 2) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 let missingOctets = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0,_x000D_
  n = str.length,_x000D_
  result = new Uint8Array(3 * (n / 4)),_x000D_
 for (let i = 0, j = 0; i < n; i += 4, j += 3) {_x000D_
  buffer =_x000D_
   getBase64Code(str.charCodeAt(i)) << 18 |_x000D_
   getBase64Code(str.charCodeAt(i + 1)) << 12 |_x000D_
   getBase64Code(str.charCodeAt(i + 2)) << 6 |_x000D_
   getBase64Code(str.charCodeAt(i + 3));_x000D_
  result[j] = buffer >> 16;_x000D_
  result[j + 1] = (buffer >> 8) & 0xFF;_x000D_
  result[j + 2] = buffer & 0xFF;_x000D_
 return result.subarray(0, result.length - missingOctets);_x000D_
export function base64encode(str, encoder = new TextEncoder()) {_x000D_
 return bytesToBase64(encoder.encode(str));_x000D_
export function base64decode(str, decoder = new TextDecoder()) {_x000D_
 return decoder.decode(base64ToBytes(str));_x000D_

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

How to find the date of a day of the week from a date using PHP?

If your date is already a DateTime or DateTimeImmutable you can use the format method.

$day_of_week = intval($date_time->format('w'));

The format string is identical to the one used by the date function.

To answer the intended question:

$date_time->modify($target_day_of_week - $day_of_week . ' days');

Split Strings into words with multiple word boundary delimiters

First of all, I don't think that your intention is to actually use punctuation as delimiters in the split functions. Your description suggests that you simply want to eliminate punctuation from the resultant strings.

I come across this pretty frequently, and my usual solution doesn't require re.

One-liner lambda function w/ list comprehension:

(requires import string):

split_without_punc = lambda text : [word.strip(string.punctuation) for word in 
    text.split() if word.strip(string.punctuation) != '']

# Call function
split_without_punc("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']

Function (traditional)

As a traditional function, this is still only two lines with a list comprehension (in addition to import string):

def split_without_punctuation2(text):

    # Split by whitespace
    words = text.split()

    # Strip punctuation from each word
    return [word.strip(ignore) for word in words if word.strip(ignore) != '']

split_without_punctuation2("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']

It will also naturally leave contractions and hyphenated words intact. You can always use text.replace("-", " ") to turn hyphens into spaces before the split.

General Function w/o Lambda or List Comprehension

For a more general solution (where you can specify the characters to eliminate), and without a list comprehension, you get:

def split_without(text: str, ignore: str) -> list:

    # Split by whitespace
    split_string = text.split()

    # Strip any characters in the ignore string, and ignore empty strings
    words = []
    for word in split_string:
        word = word.strip(ignore)
        if word != '':

    return words

# Situation-specific call to general function
import string
final_text = split_without("Hey, you - what are you doing?!", string.punctuation)
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']

Of course, you can always generalize the lambda function to any specified string of characters as well.

Caesar Cipher Function in Python

This is an improved version of the code in the answer of @amillerrhodes that works with different alphabets, not just lowercase:

def caesar(text, step, alphabets):

    def shift(alphabet):
        return alphabet[step:] + alphabet[:step]

    shifted_alphabets = tuple(map(shift, alphabets))
    joined_aphabets = ''.join(alphabets)
    joined_shifted_alphabets = ''.join(shifted_alphabets)
    table = str.maketrans(joined_aphabets, joined_shifted_alphabets)
    return text.translate(table)

Example of usage:

>>> import string
>>> alphabets = (string.ascii_lowercase, string.ascii_uppercase, string.digits)
>>> caesar('Abc-xyZ.012:789??ñç', step=4, alphabets=alphabets)

Docs on str.maketrans.
Docs on str.translate.
Docs on the string library

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

It is General sibling combinator and is explained in @Salaman's answer very well.

What I did miss is Adjacent sibling combinator which is + and is closely related to ~.

example would be

.a + .b {
  background-color: #ff0000;

  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
  • Matches elements that are .b
  • Are adjacent to .a
  • After .a in HTML

In example above it will mark 2nd li but not 4th.

   .a + .b {_x000D_
     background-color: #ff0000;_x000D_
  <li class="a">1st</li>_x000D_
  <li class="b">2nd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="a">5th</li>_x000D_


Remove directory which is not empty

return new Promise((resolve, reject) => {
  const fs = require("fs");
  // directory path
  const dir = "your/dir";

  // delete directory recursively <------
  fs.rmdir(dir, { recursive: true }, (err) => {
    if (err) {
    resolve(`${dir} is deleted!`);

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
   A  B
0  5  1
3  4  5

How to truncate the time on a DateTime object in Python?

To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:

>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>>, 2, 3)
>>> datetime.combine(dt, time.min)
datetime.datetime(2015, 2, 3, 0, 0)

The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.

tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?

"No such file or directory" but it exists

I found my solution for my Ubuntu 18 here.

sudo dpkg --add-architecture i386


sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

If hasClass then addClass to parent

Alternatively you could use:

if ($('#navigation a').is(".active")) {

How to download PDF automatically using js?

/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL; = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1); = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) &&"Chrome") < 0) {
            document.location = save.href; 
// window event not working here
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            (window.URL || window.webkitURL).revokeObjectURL(save.href);

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window =, '_blank');
    _window.document.execCommand('SaveAs', true, fileName || fileURL)

How to use?

download_file(fileURL, fileName); //call function


MySQL select where column is not empty

To check if field is NULL use IS NULL, IS NOT NULL operators.

MySql reference

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to specify the port an ASP.NET Core application is hosted on?

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urls node:
  "Urls": "http://localhost:5001"
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
public static class Program
    public static void Main(string[] args) =>

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            .ConfigureWebHostDefaults(builder =>

Or, if you're still using the web host builder instead of the generic host builder:

public class Program
    public static void Main(string[] args) =>
        new WebHostBuilder()

Calculate age given the birth date in the format YYYYMMDD

$("#birthday").change(function (){

var val=this.value;

var current_year=new Date().getFullYear();
    var Split = val.split("-");
    var birth_year=parseInt(Split[2]);


  $("#maritial_status").attr('disabled', 'disabled');
        var val2= document.getElementById("maritial_status");
        val2.value = "Not Married";
        $("#anniversary").attr('disabled', 'disabled');
        var val1= document.getElementById("anniversary");
        val1.value = "NA";

        $("#maritial_status").attr('disabled', false);
        $("#anniversary").attr('disabled', false);


Custom Adapter for List View

I know this has already been answered... but I wanted to give a more complete example.

In my example, the ListActivity that will display our custom ListView is called OptionsActivity, because in my project this Activity is going to display the different options my user can set to control my app. There are two list item types, one list item type just has a TextView and the second list item type just has a Button. You can put any widgets you like inside each list item type, but I kept this example simple.

The getItemView() method checks to see which list items should be type 1 or type 2. According to my static ints I defined up top, the first 5 list items will be list item type 1, and the last 5 list items will be list item type 2. So if you compile and run this, you will have a ListView that has five items that just contain a Button, and then five items that just contain a TextView.

Below is the Activity code, the activity xml file, and an xml file for each list item type.

public class OptionsActivity extends ListActivity {

    private static final int LIST_ITEM_TYPE_1 = 0;
    private static final int LIST_ITEM_TYPE_2 = 1;
    private static final int LIST_ITEM_TYPE_COUNT = 2;

    private static final int LIST_ITEM_COUNT = 10;
    // The first five list items will be list item type 1 
    // and the last five will be list item type 2
    private static final int LIST_ITEM_TYPE_1_COUNT = 5;

    private MyCustomAdapter mAdapter;

    public void onCreate(Bundle savedInstanceState) {
        mAdapter = new MyCustomAdapter();
        for (int i = 0; i < LIST_ITEM_COUNT; i++) {
          if (i < LIST_ITEM_TYPE_1_COUNT)
            mAdapter.addItem("item type 1");
            mAdapter.addItem("item type 2");

    private class MyCustomAdapter extends BaseAdapter {

        private ArrayList<String> mData = new ArrayList<String>();
        private LayoutInflater mInflater;

        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        public void addItem(final String item) {

        public int getItemViewType(int position) {
          if(position < LIST_ITEM_TYPE_1_COUNT)
              return LIST_ITEM_TYPE_1;
              return LIST_ITEM_TYPE_2;

        public int getViewTypeCount() {
            return LIST_ITEM_TYPE_COUNT;

        public int getCount() {
            return mData.size();

        public String getItem(int position) {
            return mData.get(position);

        public long getItemId(int position) {
            return position;

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int type = getItemViewType(position);
            if (convertView == null) {
                holder = new ViewHolder();
                switch(type) {
                    case LIST_ITEM_TYPE_1:
                        convertView = mInflater.inflate(R.layout.list_item_type1, null);
                        holder.textView = (TextView)convertView.findViewById(;
                    case LIST_ITEM_TYPE_2:
                        convertView = mInflater.inflate(R.layout.list_item_type2, null);
                        holder.textView = (TextView)convertView.findViewById(;
            } else {
                holder = (ViewHolder)convertView.getTag();
            return convertView;


    public static class ViewHolder {
        public TextView textView;



<LinearLayout xmlns:android=""

        android:layout_height="wrap_content" >



<?xml version="1.0" encoding="utf-8"?>
    android:orientation="vertical" >

        android:text="Text goes here" />



<?xml version="1.0" encoding="utf-8"?>
    android:orientation="vertical" >

        android:text="Button text goes here" />


Calculating how many minutes there are between two times

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.

How to change a PG column to NULLABLE TRUE?

From the fine manual:


There's no need to specify the type when you're just changing the nullability.

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

Overlapping Views in Android

The simples way arround is to put -40dp margin at the buttom of the top imageview

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

Checkbox angular material checked by default

// in component.ts
checked: boolean = true;
indeterminate:boolean = false;
disabled:boolean = false;

onCheck() {
    this.label = this.checked?'ON':'OFF';

// in component.html`enter code here`
<mat-checkbox class="example-margin" [color]="primary" [(ngModel)]="checked" [(indeterminate)]="indeterminate" [labelPosition]="after" [disabled]="disabled" (change)="onCheck()">

The above code should work fine. Mat checkbox allows you to make it checked/unchecked, disabled, set indeterminate state, do some operation onChange of the state etc. Refer API for more details.

How to check if a line is blank using regex

Well...I tinkered around (using notepadd++) and this is the solution I found


\n for end of line (where you start matching) -- the caret would not be of help in my case as the beginning of the row is a string \s takes any space till the next string

hope it helps

How can I check if the array of objects have duplicate property values?

Try an simple loop:

var repeat = [], tmp, i = 0;

while(i < values.length){
  repeat.indexOf(tmp = values[i++].name) > -1 ? values.pop(i--) : repeat.push(tmp)


How to put a tooltip on a user-defined function

Also you can use, this Macro to assign Descriptions to arguments and the UDF:

Private Sub RegisterMyFunction()
Application.MacroOptions _
    Macro:="SampleFunction", _      '' Your UDF name
    Description:="calculates a result based on provided inputs", _
    Category:="My UDF Category", _  '' Or use numbers, a list in the link below
    ArgumentDescriptions:=Array( _  '' One by each argument
        "is the first argument.  tell the user what it does", _
        "is the second argument.  tell the user what it does")
End Sub

Credits to Kendall and the original post here. For the UDF Categories

Remove all special characters except space from a string using JavaScript

Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.

var str = 'abc'de#;:sfjkewr47239847duifyh';

or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

Javascript array search and remove string?

You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.

Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Encoding targetEncoding = Encoding.GetEncoding(1252);
// Encode a string into an array of bytes.
Byte[] encodedBytes = targetEncoding.GetBytes(utfString);
// Show the encoded byte values.
Console.WriteLine("Encoded bytes: " + BitConverter.ToString(encodedBytes));
// Decode the byte array back to a string.
String decodedString = Encoding.Default.GetString(encodedBytes);

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

There is one more solution to set column Full text to true.

These solution for example didn't work for me

ALTER TABLE news ADD FULLTEXT(headline, story);

My solution.

  1. Right click on table
  2. Design
  3. Right Click on column which you want to edit
  4. Full text index
  5. Add
  6. Close
  7. Refresh


  1. Right click on table
  2. Design
  3. Click on column which you want to edit
  4. On bottom of mssql you there will be tab "Column properties"
  5. Full-text Specification -> (Is Full-text Indexed) set to true.


Version of mssql 2014

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties:, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

When would you use the Builder Pattern?

Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    private final int size;

    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;

    public Builder cheese(boolean value) {
      cheese = value;
      return this;

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;

    public Builder bacon(boolean value) {
      bacon = value;
      return this;

    public Pizza build() {
      return new Pizza(this);

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

Find all special characters in a column in SQL Server 2008

select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}

How to capture a JFrame's close button click event?

This may work:

jdialog.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        System.out.println("jdialog window closed event received");

    public void windowClosing(WindowEvent e) {
        System.out.println("jdialog window closing event received");


How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

You can do it with SQL Management Studio -

Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

Here is the msdn source -

How to kill a while loop with a keystroke?

The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

    while True:
except KeyboardInterrupt:

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

Is a URL allowed to contain a space?

Urls should not have spaces in them. If you need to address one that does, use its encoded value of %20

Convert a hexadecimal string to an integer efficiently in C?

As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn't matter, but in the context of this specific problem it is critically important.

You see, there's no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of representations of values. Meanwhile, values (or numbers) by themselves have no representation, so they can't be "hex" or "decimal". For example, 0xF and 15 in C syntax are two different representations of the same number.

I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to use an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from strto... group, like strtol), then convert the integer into the ASCII decimal representation (using sprintf).

If that's not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated.

.Contains() on a list of custom class objects

By default reference types have reference equality (i.e. two instances are only equal if they are the same object).

You need to override Object.Equals (and Object.GetHashCode to match) to implement your own equality. (And it is then good practice to implement an equality, ==, operator.)

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

eclipse won't start - no java virtual machine was found

Via Puppet ATG installation Centos.


No Java virtual machine could be found from your PATH


Declear variable :


Add This "{$java_home}" Java Exec

require common, java
Exec {
    path => [ "${java_home}", "/usr/bin", "/bin", "/usr/sbin", "${temp_directory}"]

How do I resolve this "ORA-01109: database not open" error?

As the error states - the database is not open - it was previously shut down, and someone left it in the middle of the startup process. They may either be intentional, or unintentional (i.e., it was supposed to be open, but failed to do so).

Assuming that's nothing wrong with the database itself, you could open it with a simple statement. (Since the question is asked specifically in the context of SQLPlus, kindly remember to put a statement terminator(Semicolon) at the end mandatorily, otherwise, it will result in an error. The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard.)


Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

How to default to other directory instead of home directory

This will do it assuming you want this to happen each time you open the command line:

echo cd ../../../d/work_space_for_my_company/project/code_source >> ~/.bashrc

Now when you open the shell it will move up three directories from home and change to code_source.

This code simply appends the line "cd ../../../d/work_space_for_my_company/project/code_source" to a file named ".bashrc". The ">>" creates a file if it does not exist and then appends. The .bashrc file is useful for running commands at start-up/log-in time (i.e. loading modules etc.)

How to combine two vectors into a data frame

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))

Remove all items from RecyclerView

This is how I cleared my recyclerview and added new items to it with animation:



//reset adapter with empty array list (it did the trick animation)
mAdapter = new MyAdapter(context, mList);


Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
> d.getFullYear(0);

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
> d = 57 + 23;
> d.getFullYear();
TypeError: undefined is not a function

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.


// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg =;
// ImageIcon icon = new ImageIcon(myImg);

// use icon here

Automatically enter SSH password with script

sshpass + autossh

One nice bonus of the already-mentioned sshpass is that you can use it with autossh, eliminating even more of the interactive inefficiency.

sshpass -p mypassword autossh -M0 -t [email protected]

This will allow autoreconnect if, e.g. your wifi is interrupted by closing your laptop.

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

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

How to redirect docker container logs to a single file?

docker logs -f <yourContainer> &> your.log &


  • -f (i.e.--follow): writes all existing logs and continues (follows) logging everything that comes next.
  • &> redirects both the standard output and standard error.
  • Likely you want to run that method in the background, thus the &.
  • You can separate output and stderr by: > output.log 2> error.log (instead of using &>).

Minimum and maximum date

From the spec, §

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

Vertically align text within a div

Andres Ilich has it right. Just in case someone misses his comment...

A.) If you only have one line of text:

  height: 200px;_x000D_
  line-height: 200px; /* <-- this is what you must define */_x000D_
<div>vertically centered text</div>

B.) If you have multiple lines of text:

  height: 200px;_x000D_
  line-height: 200px;_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  line-height: 18px; /* <-- adjust this */_x000D_
<div><span>vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text</span></div>

How do you explicitly set a new property on `window` in TypeScript?

I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.

In order for my library to use declarations I had to use the d.ts extention for the file that declares the new properties of the global object.

So in the end, the file ended up with something like:


Once created, don't forget to expose it in your public_api.ts.

That did it for me. Hope this helps.

Good Free Alternative To MS Access

NuBuilder ( might be right.

NuBuilder is a GPLv3-licensed PHP web application that requires MySQL as backend database. Users and programmers both use the web interface.

They promote it as a free, web based MS Access alternative. I'm creating my second NuBuilder application these days. The NuBuilder seems to be very actively developed, and I found it stable and well documented (provided you can stand video tutorials.)

Android splash screen image sizes to fit all devices

In my case, I used list drawable in style.xml. With layer list drawable, you have just needed one png for all screen size.

<resources xmlns:tools="">
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/flash_screen</item>
    <item name="android:windowTranslucentStatus" tools:ignore="NewApi">true</item>

and flash_screen.xml in drawable folder.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="">
    <item android:drawable="@android:color/white"></item>
        <bitmap android:src="@drawable/background_noizi" android:gravity="center"></bitmap>

"background_noizi" is a png file in the drawable folder. I hope this helps.

How to deal with ModalDialog using selenium webdriver?

I have tried it, it works for you.

String mainWinHander = webDriver.getWindowHandle();

// code for clicking button to open new window is ommited

//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();

for(String handle : handles)
        // Here will block for ever. No exception and timeout!
        WebDriver popup = webDriver.switchTo().window(handle);
        // do something with popup

How to check the extension of a filename in a bash script?

You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.

If you feel comfortable with using the extension you can use grep to see if it matches.

Check whether number is even or odd

Another easy way to do it without using if/else condition (works for both positive and negative numbers):

int n = 8;
List<String> messages = Arrays.asList("even", "odd");


For an Odd no., the expression will return '1' as remainder, giving

messages.get(1) = 'odd' and hence printing 'odd'

else, 'even' is printed when the expression comes up with result '0'

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
            strValue = _tags["101"];

        if (_tags.TryGetValue("101", out strValue))

Angular: How to update queryParams without changing route


this.router.navigate([], { 
  queryParams: {
    query: value

will work for same route navigation other than single quotes.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}


<!DOCTYPE html>
<html lang="en" xmlns="">
    <meta charset="utf-8" />
    <script src="angular.js"></script>

    <div ng-app="myApp" ng-controller="personController">
            <tr> <th>First Name</th> <th>Last Name</th> </tr>
            <tr ng-repeat="person in people track by $index">
                <td><input type="button" value="Select" ng-click="showDetails($index)" /></td>

        </table> <hr />
            <tr ng-repeat="person1 in items track by $index">
        <span>   {{sayHello()}}</span>
    <script> var myApp = angular.module("myApp", []);
        myApp.controller("personController", ['$scope', function ($scope)
            $scope.people = [{ firstName: "F1", lastName: "L1" },
                { firstName: "F2", lastName: "L2" }, 
                { firstName: "F3", lastName: "L3" }, 
                { firstName: "F4", lastName: "L4" }, 
                { firstName: "F5", lastName: "L5" }]
            $scope.items = [];
            $scope.selectedPerson = $scope.people[0];
            $scope.showDetails = function (ind) 
                $scope.selectedPerson = $scope.people[ind];
            $scope.sayHello = function ()
                return $scope.items.firstName;
        }]) </script>

Provisioning Profiles menu item missing from Xcode 5

For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.

If anyone gets this far and is still struggling, here's what I did:

  1. Close xcode 5
  2. Open xcode 4.6.2
  3. Go to Window->Organizer->Provisioning Profiles
  4. Press Refresh arrow on bottom right

When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.

Where is SQLite database stored on disk?

A SQLite database is a regular file. It is created in your script current directory.

What is "Linting"?

Lint was the name of a program that would go through your C code and identify problems before you compiled, linked, and ran it. It was a static checker, much like FindBugs today for Java.

Like Google, "lint" became a verb that meant static checking your source code.

Absolute position of an element on the screen using jQuery

For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..

function AbsoluteCoordinates($element) {
    var sTop = $(window).scrollTop();
    var sLeft = $(window).scrollLeft();
    var w = $element.width();
    var h = $element.height();
    var offset = $element.offset(); 
    var $p = $element;
    while(typeof $p == 'object') {
        var pOffset = $p.parent().offset();
        if(typeof pOffset == 'undefined') break;
        offset.left = offset.left + (pOffset.left); = + (;
        $p = $p.parent();

    var pos = {
          left: offset.left + sLeft,
          right: offset.left + w + sLeft,
          top: + sTop,
          bottom: + h + sTop,
    } = { x: pos.left, y: }; = { x: pos.right, y: }; = { x: pos.left, y: pos.bottom }; = { x: pos.right, y: pos.bottom };
    //console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + +' - bottom: ' + pos.bottom  );
    return pos;

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Why is 2 * (i * i) faster than 2 * i * i in Java?

There is a slight difference in the ordering of the bytecode.

2 * (i * i):


vs 2 * i * i:


At first sight this should not make a difference; if anything the second version is more optimal since it uses one slot less.

So we need to dig deeper into the lower level (JIT)1.

Remember that JIT tends to unroll small loops very aggressively. Indeed we observe a 16x unrolling for the 2 * (i * i) case:

030   B2: # B2 B3 <- B1 B2  Loop: B2-B2 inner main of N18 Freq: 1e+006
030     addl    R11, RBP    # int
033     movl    RBP, R13    # spill
036     addl    RBP, #14    # int
039     imull   RBP, RBP    # int
03c     movl    R9, R13 # spill
03f     addl    R9, #13 # int
043     imull   R9, R9  # int
047     sall    RBP, #1
049     sall    R9, #1
04c     movl    R8, R13 # spill
04f     addl    R8, #15 # int
053     movl    R10, R8 # spill
056     movdl   XMM1, R8    # spill
05b     imull   R10, R8 # int
05f     movl    R8, R13 # spill
062     addl    R8, #12 # int
066     imull   R8, R8  # int
06a     sall    R10, #1
06d     movl    [rsp + #32], R10    # spill
072     sall    R8, #1
075     movl    RBX, R13    # spill
078     addl    RBX, #11    # int
07b     imull   RBX, RBX    # int
07e     movl    RCX, R13    # spill
081     addl    RCX, #10    # int
084     imull   RCX, RCX    # int
087     sall    RBX, #1
089     sall    RCX, #1
08b     movl    RDX, R13    # spill
08e     addl    RDX, #8 # int
091     imull   RDX, RDX    # int
094     movl    RDI, R13    # spill
097     addl    RDI, #7 # int
09a     imull   RDI, RDI    # int
09d     sall    RDX, #1
09f     sall    RDI, #1
0a1     movl    RAX, R13    # spill
0a4     addl    RAX, #6 # int
0a7     imull   RAX, RAX    # int
0aa     movl    RSI, R13    # spill
0ad     addl    RSI, #4 # int
0b0     imull   RSI, RSI    # int
0b3     sall    RAX, #1
0b5     sall    RSI, #1
0b7     movl    R10, R13    # spill
0ba     addl    R10, #2 # int
0be     imull   R10, R10    # int
0c2     movl    R14, R13    # spill
0c5     incl    R14 # int
0c8     imull   R14, R14    # int
0cc     sall    R10, #1
0cf     sall    R14, #1
0d2     addl    R14, R11    # int
0d5     addl    R14, R10    # int
0d8     movl    R10, R13    # spill
0db     addl    R10, #3 # int
0df     imull   R10, R10    # int
0e3     movl    R11, R13    # spill
0e6     addl    R11, #5 # int
0ea     imull   R11, R11    # int
0ee     sall    R10, #1
0f1     addl    R10, R14    # int
0f4     addl    R10, RSI    # int
0f7     sall    R11, #1
0fa     addl    R11, R10    # int
0fd     addl    R11, RAX    # int
100     addl    R11, RDI    # int
103     addl    R11, RDX    # int
106     movl    R10, R13    # spill
109     addl    R10, #9 # int
10d     imull   R10, R10    # int
111     sall    R10, #1
114     addl    R10, R11    # int
117     addl    R10, RCX    # int
11a     addl    R10, RBX    # int
11d     addl    R10, R8 # int
120     addl    R9, R10 # int
123     addl    RBP, R9 # int
126     addl    RBP, [RSP + #32 (32-bit)]   # int
12a     addl    R13, #16    # int
12e     movl    R11, R13    # spill
131     imull   R11, R13    # int
135     sall    R11, #1
138     cmpl    R13, #999999985
13f     jl     B2   # loop end  P=1.000000 C=6554623.000000

We see that there is 1 register that is "spilled" onto the stack.

And for the 2 * i * i version:

05a   B3: # B2 B4 <- B1 B2  Loop: B3-B2 inner main of N18 Freq: 1e+006
05a     addl    RBX, R11    # int
05d     movl    [rsp + #32], RBX    # spill
061     movl    R11, R8 # spill
064     addl    R11, #15    # int
068     movl    [rsp + #36], R11    # spill
06d     movl    R11, R8 # spill
070     addl    R11, #14    # int
074     movl    R10, R9 # spill
077     addl    R10, #16    # int
07b     movdl   XMM2, R10   # spill
080     movl    RCX, R9 # spill
083     addl    RCX, #14    # int
086     movdl   XMM1, RCX   # spill
08a     movl    R10, R9 # spill
08d     addl    R10, #12    # int
091     movdl   XMM4, R10   # spill
096     movl    RCX, R9 # spill
099     addl    RCX, #10    # int
09c     movdl   XMM6, RCX   # spill
0a0     movl    RBX, R9 # spill
0a3     addl    RBX, #8 # int
0a6     movl    RCX, R9 # spill
0a9     addl    RCX, #6 # int
0ac     movl    RDX, R9 # spill
0af     addl    RDX, #4 # int
0b2     addl    R9, #2  # int
0b6     movl    R10, R14    # spill
0b9     addl    R10, #22    # int
0bd     movdl   XMM3, R10   # spill
0c2     movl    RDI, R14    # spill
0c5     addl    RDI, #20    # int
0c8     movl    RAX, R14    # spill
0cb     addl    RAX, #32    # int
0ce     movl    RSI, R14    # spill
0d1     addl    RSI, #18    # int
0d4     movl    R13, R14    # spill
0d7     addl    R13, #24    # int
0db     movl    R10, R14    # spill
0de     addl    R10, #26    # int
0e2     movl    [rsp + #40], R10    # spill
0e7     movl    RBP, R14    # spill
0ea     addl    RBP, #28    # int
0ed     imull   RBP, R11    # int
0f1     addl    R14, #30    # int
0f5     imull   R14, [RSP + #36 (32-bit)]   # int
0fb     movl    R10, R8 # spill
0fe     addl    R10, #11    # int
102     movdl   R11, XMM3   # spill
107     imull   R11, R10    # int
10b     movl    [rsp + #44], R11    # spill
110     movl    R10, R8 # spill
113     addl    R10, #10    # int
117     imull   RDI, R10    # int
11b     movl    R11, R8 # spill
11e     addl    R11, #8 # int
122     movdl   R10, XMM2   # spill
127     imull   R10, R11    # int
12b     movl    [rsp + #48], R10    # spill
130     movl    R10, R8 # spill
133     addl    R10, #7 # int
137     movdl   R11, XMM1   # spill
13c     imull   R11, R10    # int
140     movl    [rsp + #52], R11    # spill
145     movl    R11, R8 # spill
148     addl    R11, #6 # int
14c     movdl   R10, XMM4   # spill
151     imull   R10, R11    # int
155     movl    [rsp + #56], R10    # spill
15a     movl    R10, R8 # spill
15d     addl    R10, #5 # int
161     movdl   R11, XMM6   # spill
166     imull   R11, R10    # int
16a     movl    [rsp + #60], R11    # spill
16f     movl    R11, R8 # spill
172     addl    R11, #4 # int
176     imull   RBX, R11    # int
17a     movl    R11, R8 # spill
17d     addl    R11, #3 # int
181     imull   RCX, R11    # int
185     movl    R10, R8 # spill
188     addl    R10, #2 # int
18c     imull   RDX, R10    # int
190     movl    R11, R8 # spill
193     incl    R11 # int
196     imull   R9, R11 # int
19a     addl    R9, [RSP + #32 (32-bit)]    # int
19f     addl    R9, RDX # int
1a2     addl    R9, RCX # int
1a5     addl    R9, RBX # int
1a8     addl    R9, [RSP + #60 (32-bit)]    # int
1ad     addl    R9, [RSP + #56 (32-bit)]    # int
1b2     addl    R9, [RSP + #52 (32-bit)]    # int
1b7     addl    R9, [RSP + #48 (32-bit)]    # int
1bc     movl    R10, R8 # spill
1bf     addl    R10, #9 # int
1c3     imull   R10, RSI    # int
1c7     addl    R10, R9 # int
1ca     addl    R10, RDI    # int
1cd     addl    R10, [RSP + #44 (32-bit)]   # int
1d2     movl    R11, R8 # spill
1d5     addl    R11, #12    # int
1d9     imull   R13, R11    # int
1dd     addl    R13, R10    # int
1e0     movl    R10, R8 # spill
1e3     addl    R10, #13    # int
1e7     imull   R10, [RSP + #40 (32-bit)]   # int
1ed     addl    R10, R13    # int
1f0     addl    RBP, R10    # int
1f3     addl    R14, RBP    # int
1f6     movl    R10, R8 # spill
1f9     addl    R10, #16    # int
1fd     cmpl    R10, #999999985
204     jl     B2   # loop end  P=1.000000 C=7419903.000000

Here we observe much more "spilling" and more accesses to the stack [RSP + ...], due to more intermediate results that need to be preserved.

Thus the answer to the question is simple: 2 * (i * i) is faster than 2 * i * i because the JIT generates more optimal assembly code for the first case.

But of course it is obvious that neither the first nor the second version is any good; the loop could really benefit from vectorization, since any x86-64 CPU has at least SSE2 support.

So it's an issue of the optimizer; as is often the case, it unrolls too aggressively and shoots itself in the foot, all the while missing out on various other opportunities.

In fact, modern x86-64 CPUs break down the instructions further into micro-ops (µops) and with features like register renaming, µop caches and loop buffers, loop optimization takes a lot more finesse than a simple unrolling for optimal performance. According to Agner Fog's optimization guide:

The gain in performance due to the µop cache can be quite considerable if the average instruction length is more than 4 bytes. The following methods of optimizing the use of the µop cache may be considered:

  • Make sure that critical loops are small enough to fit into the µop cache.
  • Align the most critical loop entries and function entries by 32.
  • Avoid unnecessary loop unrolling.
  • Avoid instructions that have extra load time
    . . .

Regarding those load times - even the fastest L1D hit costs 4 cycles, an extra register and µop, so yes, even a few accesses to memory will hurt performance in tight loops.

But back to the vectorization opportunity - to see how fast it can be, we can compile a similar C application with GCC, which outright vectorizes it (AVX2 is shown, SSE2 is similar)2:

  vmovdqa ymm0, YMMWORD PTR .LC0[rip]
  vmovdqa ymm3, YMMWORD PTR .LC1[rip]
  xor eax, eax
  vpxor xmm2, xmm2, xmm2
  vpmulld ymm1, ymm0, ymm0
  inc eax
  vpaddd ymm0, ymm0, ymm3
  vpslld ymm1, ymm1, 1
  vpaddd ymm2, ymm2, ymm1
  cmp eax, 125000000      ; 8 calculations per iteration
  jne .L2
  vmovdqa xmm0, xmm2
  vextracti128 xmm2, ymm2, 1
  vpaddd xmm2, xmm0, xmm2
  vpsrldq xmm0, xmm2, 8
  vpaddd xmm0, xmm2, xmm0
  vpsrldq xmm1, xmm0, 4
  vpaddd xmm0, xmm0, xmm1
  vmovd eax, xmm0

With run times:

  • SSE: 0.24 s, or 2 times as fast.
  • AVX: 0.15 s, or 3 times as fast.
  • AVX2: 0.08 s, or 5 times as fast.

1 To get JIT generated assembly output, get a debug JVM and run with -XX:+PrintOptoAssembly

2 The C version is compiled with the -fwrapv flag, which enables GCC to treat signed integer overflow as a two's-complement wrap-around.

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);

How to execute a shell script from C in Linux?

A simple way is.....

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
    puts("Will execute sh with the following script :");
    puts("Starting now:");
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;

Say thanks to
Yoda @

Listing all extras of an Intent

I noticed in the Android source that almost every operation forces the Bundle to unparcel its data. So if (like me) you need to do this frequently for debugging purposes, the below is very quick to type:

Bundle extras = getIntent().getExtras();
extras.isEmpty(); // unparcel

How to order a data frame by one descending and one ascending column?

I'm afraid Roman Luštrik's answer is wrong. It works on this input by chance. Consider for example its output on a very similar input (with an additional line similar to the original line 3 with "c" in the I2 column):

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
3  1  5  6 55 48 60  6  f
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

This is not the desired result: the first three values of I2 are f b c instead of b c f, which would be expected since the secondary sort is I2 in ascending order.

To get the reverse order of I2, you want the large values to be small and vice versa. For numeric values multiplying by -1 will do it, but for characters its a bit more tricky. A general solution for characters/strings would be to go through factors, reverse the levels (to make large values small and small values large) and change the factor back to characters:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

levels(f) = rev(levels(f))
rum[order(rum$I1, as.character(f), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

Wait for page load in Selenium

For implicit wait you can use something like following:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

In order for webpage to wait for a specific object to be visible or cerntain condition to be true. You can use wait feather of web driver.

//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);  

In Java, another option is to sleep the thread for specific time.

//This line will cause thread to sleep for seconds as variable

I created a method to simplify thread.sleep method

public static void wait_time(int seconds){
    try {
        }catch (InterruptedException e) {
        // TODO Auto-generated catch block

Use the method as wait_time(10); The thread will sleep for 10 seconds.

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

mysql command for showing current configuration variables

What you are looking for is this:


You can modify it further like any query:


How to execute a program or call a system command from Python

Shameless plug, I wrote a library for this :P

It's basically a wrapper for popen and shlex for now. It also supports piping commands so you can chain commands easier in Python. So you can do things like:

ex('echo hello') | "awk '{print $2}'"

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

I think that in this question is missing one important information.

How many records will you insert?

  1. If from 1 to cca. 10.000 then you should use SQL statement (Like they said it is easy to understand and it is easy to write).
  2. If from cca. 10.000 to cca. 100.000 then you should use cursor, but you should add logic to commit on every 10.000 records.
  3. If from cca. 100.000 to millions then you should use bulk collect for better performance.

Attaching click to anchor tag in angular

I think you are not letting Angular work for you.

In angular 2:

  1. Remove the href tag from <a> to prevent a page forwarding.
  2. Then just add your usual Angular click attribute and function.
  3. Add to style: "cursor: pointer" to make it act like a button

Algorithm to find Largest prime factor of a number

    //this method skips unnecessary trial divisions and makes 
    //trial division more feasible for finding large primes

    public static void main(String[] args) 
        long n= 1000000000039L; //this is a large prime number 
        long i = 2L;
        int test = 0;

        while (n > 1)
            while (n % i == 0)
                n /= i;     


            if(i*i > n && n > 1) 
                System.out.println(n); //prints n if it's prime
                test = 1;

        if (test == 0)  
            System.out.println(i-1); //prints n if it's the largest prime factor

Is there a way to make numbers in an ordered list bold?

Another easy possibility would be to wrap the list item content into a <p>, style the <li> as bold and the <p> as regular. This would be also preferable from an IA point of view, especially when <li>s can contain sub-lists (to avoid mixing text nodes with block level elements).

Full example for your convenience:

        <title>Ordered list items with bold numbers</title>
            ol li {
            li > p {
                <p>List Item 1</p>
                <p>Liste Item 2</p>
                        <p>Sub List Item 1</p>
                        <p>Sub List Item 2</p>
                <p>List Item 3.</p>

If you prefer a more generic approach (that would also cover other scenarios like <li>s with descendants other than <p>, you might want to use li > * instead of li > p:

        <title>Ordered list items with bold numbers</title>
            ol li {
            li > * {
                <p>List Item 1</p>
                <p>Liste Item 2</p>
                        <p>Sub List Item 1</p>
                        <p>Sub List Item 2</p>
                <p>List Item 3.</p>
                <code>List Item 4.</code>

(Check the list item 4 here which is ol/li/code and not ol/li/p/code here.)

Just make sure to use the selector li > * and not li *, if you only want to style block level descendants as regular, but not also inlines like "foo <strong>bold word</strong> foo."

Setting up JUnit with IntelliJ IDEA

I needed to enable the JUnit plugin, after I linked my project with the jar files.

To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.

vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to

C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\

and add these jar files:


How to capture UIView to UIImage without loss of quality on retina display

Swift 3.0 implementation

extension UIView {
    func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!
        return snapshotImage

Trim string in JavaScript?

All browsers since IE9+ have trim() method for strings:

" \n test \n ".trim(); // returns "test" here

For those browsers who does not support trim(), you can use this polyfill from MDN:

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');

That said, if using jQuery, $.trim(str) is also available and handles undefined/null.

See this:

String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};

String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};

String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};

$ is not a function - jQuery error

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 

change this to

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
        $("ol li:nth-child(1)").addClass('olli1');
        $("ol li:nth-child(2)").addClass("olli2");
        $("ol li:nth-child(3)").addClass("olli3");
        $("ol li:nth-child(4)").addClass("olli4");
        $("ol li:nth-child(5)").addClass("olli5");
        $("ol li:nth-child(6)").addClass("olli6");
        $("ol li:nth-child(7)").addClass("olli7");
        $("ol li:nth-child(8)").addClass("olli8");
        $("ol li:nth-child(9)").addClass("olli9");
        $("ol li:nth-child(10)").addClass("olli10");
        $("ol li:nth-child(11)").addClass("olli11");
        $("ol li:nth-child(12)").addClass("olli12");
        $("ol li:nth-child(13)").addClass("olli13");
        $("ol li:nth-child(14)").addClass("olli14");
        $("ol li:nth-child(15)").addClass("olli15");
        $("ol li:nth-child(16)").addClass("olli16");
        $("ol li:nth-child(17)").addClass("olli17");
        $("ol li:nth-child(18)").addClass("olli18");
        $("ol li:nth-child(19)").addClass("olli19");
        $("ol li:nth-child(20)").addClass("olli20"); 

How to implement the ReLU function in Numpy

This is more precise implementation:

def ReLU(x):
    return abs(x) * (x > 0)

Self-references in object literals / initializers

Other approach would be to declare the object first before assigning properties into it:

const foo = {};
foo.a = 5;
foo.b = 6;
foo.c = foo.a + foo.b;  // Does work
foo.getSum = () => foo.a + foo.b + foo.c;  // foo.getSum() === 22

With that, you can use the object variable name to access the already assigned values.
Best for config.js file.

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

How to add an Android Studio project to GitHub

If you are using the latest version of Android studio. then you don't need to install additional software for Git other than GIT itself -


  1. Create an account on Github -
  2. Install Git
  3. Open your working project in Android studio
  4. GoTo - File -> Settings -> Version Controll -> GitHub
  5. Enter Login and Password which you have created just on Git Account and click on test
  6. Once all credentials are true - it shows Success message. o.w Invalid Cred.
  7. Now click on VCS in android studio menu bar
  8. Select Import into Version Control -> Share Project on GitHub
  9. The popup dialog will occure contains all your files with check mark, do ok or commit all
  10. At next time whenever you want to push your project just click on VCS - > Commit Changes -> Commmit and Push.

That's it. You can find your project on your github now

How do I search for files in Visual Studio Code?

I'm using VSCode 1.12.1

OSX press : Cmd + p

How to convert XML to java.util.Map and vice versa

In my case I convert DBresponse to XML in Camel ctx. JDBC executor return the ArrayList (rows) with LinkedCaseInsensitiveMap (single row). Task - create XML object based on DBResponce.

import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.springframework.util.LinkedCaseInsensitiveMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class ConvertDBToXMLProcessor implements Processor {

    public void process(List body) {

        if (body instanceof ArrayList) {
            ArrayList<LinkedCaseInsensitiveMap> rows = (ArrayList) body;

            DocumentBuilder builder = null;
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.newDocument();
            Element rootElement = document.createElement("DBResultSet");

            for (LinkedCaseInsensitiveMap row : rows) {
                Element newNode = document.createElement("Row");
                row.forEach((key, value) -> {
                    if (value != null) {
                        Element newKey = document.createElement((String) key);

            * If you need return string view instead org.w3c.dom.Document
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource domSource = new DOMSource(document);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.transform(domSource, result);

            // return document
            // return writer.toString()


How to view file diff in git before commit

Did you try -v (or --verbose) option for git commit? It adds the diff of the commit in the message editor.

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

Getting checkbox values on submit

Just for printing you can use as below :




increase the java heap size permanently?

what platform are you running?..
if its unix, maybe adding

alias java='java -Xmx1g'  

to .bashrc (or similar) work

edit: Changing XmX to Xmx

Animate element transform rotate

In my opinion, jQuery's animate is a bit overused, compared to the CSS3 transition, which performs such animation on any 2D or 3D property. Also I'm afraid, that leaving it to the browser and by forgetting the layer called JavaScript could lead to spare CPU juice - specially, when you wish to blast with the animations. Thus, I like to have animations where the style definitions are, since you define functionality with JavaScript. The more presentation you inject into JavaScript, the more problems you'll face later on.

All you have to do is to use addClass to the element you wish to animate, where you set a class that has CSS transition properties. You just "activate" the animation, which stays implemented on the pure presentation layer.


// with jQuery

// without jQuery library
document.getElementById("element").className += "Animate";

One could easly remove a class with jQuery, or remove a class without library.


    color      : white;

    transition        : .4s linear;
    color             : red;
     * Not that ugly as the JavaScript approach.
     * Easy to maintain, the most portable solution.
    -webkit-transform : rotate(90deg);


<span id="element">

This is a fast and convenient solution for most use cases.

I also use this when I want to implement a different styling (alternative CSS properties), and wish to change the style on-the-fly with a global .5s animation. I add a new class to the BODY, while having alternative CSS in a form like this:




BODY.Alternative #element{
    color      : blue;
    transition : .5s linear;

This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class.

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.


Set Focus on EditText

Darwind code didn't show the keyboard.

This works for me:

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(_searchText, InputMethodManager.SHOW_IMPLICIT);

in case the keyboard is not showing, try to force:

        imm.showSoftInput(_searchText, InputMethodManager.SHOW_FORCED);

How to get last key in an array?

As of PHP >= 7.3 array_key_last() is the best way to get the last key of any of an array. Using combination of end(), key() and reset() just to get last key of an array is outrageous.

$array = array("one" => bird, "two" => "fish", 3 => "elephant");
$key = array_key_last($array);
var_dump($key) //output 3

compare that to

$key = key($array)
var_dump($key) //output 3

You must reset array for the pointer to be at the beginning if you are using combination of end() and key()

How to reset settings in Visual Studio Code?

Steps to reset on Windows:

  • Press 'Windows-Key"+R , and enter %APPDATA%\Code\User

    enter image description here

    And delete 'setting.json' at this location.

  • Press 'Windows-Key"+R , and enter %USERPROFILE%.vscode\extensions

    enter image description here

    And delete all the extensions there.


After two vote downs added images to make it more clear :)

How to force HTTPS using a web.config file

In .Net Core, follow the instructions at

In your startup.cs add the following:

// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
    services.Configure<MvcOptions>(options =>
        options.Filters.Add(new RequireHttpsAttribute());
    });`enter code here`

To redirect Http to Https, add the following in the startup.cs

// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

    var options = new RewriteOptions()


How to allow only numeric (0-9) in HTML inputbox using jQuery?

Refactored the accepted answer so that comments no longer need to used because I hate comments. Also this is easier to test with jasmine.

    allowBackspaceDeleteTabEscapeEnterPress: function(event){
    return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
allowContorlAPress: function(event){
    return (event.keyCode == 65 && event.ctrlKey === true)
allowHomeEndLeftRightPress: function(event){
    return (event.keyCode >= 35 && event.keyCode <= 39)
theKeyPressedIsEditRelated: function (event) {
    return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
            || this.allowContorlAPress(event)
            || this.allowHomeEndLeftRightPress(event));
isNotFromTheNumKeyPad: function (event) {
    return (event.keyCode < 96 || event.keyCode > 105);
isNotFromTopRowNumberKeys: function (event) {
    return (event.keyCode < 48 || event.keyCode > 57);
theKeyIsNonNumeric: function (event) {
   return (event.shiftKey
           || (this.isNotFromTopRowNumberKeys(event)
                && this.isNotFromTheNumKeyPad(event)));
bindInputValidator: function(){
    $('.myinputclassselector').keydown(function (event) {
        if(this.validateKeyPressEvent(event)) return false;
validateKeyPressEvent: function(event){
    } else {
        if (this.theKeyIsNonNumeric(event)) {

How to open a folder in Windows Explorer from VBA?

Thanks to many of the answers above and elsewhere, this was my solution to a similar problem to the OP. The problem for me was creating a button in Word that asks the user for a network address, and pulls up the LAN resources in an Explorer window.

Untouched, the code would take you to \\\Test, so edit as you see fit. I'm just a monkey on a keyboard, here, so all comments and suggestions are welcome.

Private Sub CommandButton1_Click()
    Dim ipAddress As Variant
    On Error GoTo ErrorHandler

    ipAddress = InputBox("Please enter the IP address of the network resource:", "Explore a network resource", "\\")
    If ipAddress <> "" Then
        ThisDocument.FollowHyperlink ipAddress & "\Test"
    End If

        Exit Sub

        If Err.Number = "4120" Then
            GoTo ExitPoint
        ElseIf Err.Number = "4198" Then
            MsgBox "Destination unavailable"
            GoTo ExitPoint
        End If

        MsgBox "Error " & Err.Number & vbCrLf & Err.Description
        Resume ExitPoint

End Sub

Practical uses of different data structures

Few more Practical Application of data structures

Red-Black Trees (Used when there is frequent Insertion/Deletion and few searches) - K-mean Clustering using red black tree, Databases, Simple-minded database, searching words inside dictionaries, searching on web

AVL Trees (More Search and less of Insertion/Deletion) - Data Analysis and Data Mining and the applications which involves more searches

Min Heap - Clustering Algorithms

Why is Maven downloading the maven-metadata.xml every time?

I suppose because you didn't specify plugin version so it triggers the download of associated metadata in order to get the last one.

Otherwise did you try to force local repo usage using -o ?

Regular expression for matching HH:MM time format

Try the following


Note: I was assuming the javascript regex engine. If it's different than that please let me know.

HTTP Basic Authentication - what's the expected web browser experience?

If there are no credentials provided in the request headers, the following is the minimum response required for IE to prompt the user for credentials and resubmit the request.

Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
Response.AddHeader("WWW-Authenticate", "Basic");

Mongoose's find method with $or condition does not work properly

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
    if(!err) res.send(docs);

Session only cookies with Javascript

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    return false;
  if(getCookie("KoiMilGaya")) {
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

public class MyInstaller : Installer
    public HelloInstaller()
        : base()

    public override void Commit(IDictionary mySavedState)

    public override void Install(IDictionary stateSaver)

    public override void Uninstall(IDictionary savedState)

    public override void Rollback(IDictionary savedState)

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

How to pass variable number of arguments to a PHP function

In a new Php 5.6, you can use ... operator instead of using func_get_args().

So, using this, you can get all the parameters you pass:

function manyVars(...$params) {

How to remove all click event handlers using jQuery?


C# SQL Server - Passing a list to a stored procedure

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

ArrayList insertion and retrieval order

If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.

Select distinct values from a list using LINQ in C#


var newList = 
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}

How Do I Make Glyphicons Bigger? (Change Size?)

For ex .. add class:

btn-lg - LARGE

btn-sm - SMALL

btn-xs - Very small

<button type=button class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star

<button type=button class="btn btn-default">
<span class="glyphicon glyphicon-star" aria-hidden=true></span>Star

 <button type=button class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star

<button type=button class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star

Ref link Bootstrap : Glyphicons Bootstrap

jQuery UI Dialog with ASP.NET button postback

Primarily it's because jQuery moves the dialog outside of the form tags using the DOM. Move it back inside the form tags and it should work fine. You can see this by inspecting the element in Firefox.

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");



References :

  2. Java - sending HTTP parameters via POST method easily

"Could not load type [Namespace].Global" causing me grief

In my situation it was related to Web Site/Web Application type of the project. We recently moved to MVC and had to change it to Web Application.

So, the solution was simple: select your web-site in Solution Explorer and remove it from the solution, then right click on the solution and select Add -> Existing Project (not Web Site), recompile the web-site.

Run CSS3 animation only once (at page loading)

So i just found a solution for that: In the hover animation do this:

animation: hover 1s infinite alternate ease-in-out,splash 1;