Programs & Examples On #Nfs

NFS is an acronym for Network File System, a network file system developed by Sun Microsystems most often associated with the Unix family of operating systems.

Force unmount of NFS-mounted directory

Your NFS server disappeared.

Ideally your best bet is if the NFS server comes back.

If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.

If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.

Finally, I'd guess you need to reboot.

Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.

C# int to byte[]

Here's another way to do it: as we all know 1x byte = 8x bits and also, a "regular" integer (int32) contains 32 bits (4 bytes). We can use the >> operator to shift bits right (>> operator does not change value.)

int intValue = 566;

byte[] bytes = new byte[4];

bytes[0] = (byte)(intValue >> 24);
bytes[1] = (byte)(intValue >> 16);
bytes[2] = (byte)(intValue >> 8);
bytes[3] = (byte)intValue;

Console.WriteLine("{0} breaks down to : {1} {2} {3} {4}",
    intValue, bytes[0], bytes[1], bytes[2], bytes[3]);

Vagrant error : Failed to mount folders in Linux guest

Your log complains about not finding exportfs: sudo: /usr/bin/exportfs: command not found

The exportfs makes local directories available for NFS clients to mount.

'str' object does not support item assignment in Python

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

Difference between binary semaphore and mutex

Best Solution

The only difference is

1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.

2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.

How do I install a pip package globally instead of locally?

Where does pip installations happen in python?

I will give a windows solution which I was facing and took a while to solve.

First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>, it will be by default installed globally (if you have not activated a virtual enviroment). Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.

pip is installing the said packages but not I cannot use them?

For this pip might be giving you a warning that the pip executables like pip3.exe, pip.exe are not on your path variable. For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\ ) to your enviromental variables. After this restart your cmd, and now try to use your installed python package. It should work now.

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

Determine the process pid listening on a certain port

on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

Display image as grayscale using matplotlib

@unutbu's answer is quite close to the right answer.

By default, plt.imshow() will try to scale your (MxN) array data to 0.0~1.0. And then map to 0~255. For most natural taken images, this is fine, you won't see a different. But if you have narrow range of pixel value image, say the min pixel is 156 and the max pixel is 234. The gray image will looks totally wrong. The right way to show an image in gray is

from matplotlib.colors import NoNorm

Let's see an example:

this is the origianl image: original

this is using defaul norm setting,which is None: wrong pic

this is using NoNorm setting,which is NoNorm(): right pic

jQuery - Disable Form Fields

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">
  $(document).ready(function() {
      $("#suburb").blur(function() {
          if ($(this).val() != '')
              $("#post_code").attr("disabled", "disabled");

      $("#post_code").blur(function() {
          if ($(this).val() != '')
              $("#suburb").attr("disabled", "disabled");

You'll also need to add a value attribute to the first option under your select element:

<option value=""></option>

How do I install the OpenSSL libraries on Ubuntu?

How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?

If you're linking with -lfoo then the library is likely The library itself is probably part of the libfoo package, and the headers are in the libfoo-dev package as you've discovered.

Some people use the GUI "synaptic" app (sudo synaptic) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get supports bash completion.

Try typing sudo apt-get install libssl and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).

Bash completion is actually very useful... for example, you can also get a list of commands that apt-get supports by typing sudo apt-get and then hitting tab.

Convert IQueryable<> type object to List<T> type?

System.Linq has ToList() on IQueryable<> and IEnumerable<>. It will cause a full pass through the data to put it into a list, though. You loose your deferred invoke when you do this. Not a big deal if it is the consumer of the data.

What is the difference between XML and XSD?

Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.

An XML file is an instance of XSD as it uses the rules defined in the XSD.

How do I encode/decode HTML entities in Ruby?

I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.


a = Nokogiri::HTML.parse "foo&nbsp;b&auml;r"    
=> "foo bär"


a = Nokogiri::HTML.parse "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
=> "¡I'm highly annoyed with character references!"

Replace multiple strings at once

You might want to look into a JS library called phpJS.

It allows you to use the str_replace function similarly to how you would use it in PHP. There are also plenty more php functions "ported" over to JavaScript.

Inputting a default image in case the src attribute of an html <img> is not valid?

Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:

<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->

It might be off-topic, but it resolved my own issue and it might help someone else too.

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c =;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

Could not load file or assembly 'EntityFramework' after downgrading EF -->

I had a similar issue:

  1. On my ASP.NET MVC project, I've added a Sql Server Compact database (sdf) to my App_Data folder. VS added a reference to EntityFramework.dll, version 4.* . The web.config file was updated appropriately with the 4.* configuration.

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

  2. I've added a new project to my solution (a Data Access Layer project). Here I've added an EDMX file. VS added a reference to EntityFramework.dll, version 5.0. The App.config file was updated appropriately with the 5.0 configuration

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

On execution, when reading from the database the app always thrown the exception Could not load file or assembly 'EntityFramework, Version= ....

The issue was fixed by removing the EntityFramework.dll v4.0 from my MVC project. I've also updated the web.config file with the correct 5.0 version. Then everything worked as expected.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

List method to delete last element in list as well as all elements

you can use lst.pop() or del lst[-1]

pop() removes and returns the item, in case you don't want have a return use del

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

The difference between encodeURI() and encodeURIComponent() are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:

Table with the ten differences between encodeURI and encodeURIComponent

I generated this table easily with console.table in Google Chrome with this code:

var arr = [];_x000D_
for(var i=0;i<256;i++) {_x000D_
  var char=String.fromCharCode(i);_x000D_
  if(encodeURI(char)!==encodeURIComponent(char)) {_x000D_

Add User to Role ASP.NET Identity

While I agree with the other answers regarding the RoleManager, I would advice to examine the possibility to implement Authorization through Claims (Expressing Roles as Claims).

Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.

In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When the IsInRole() method is called, there is a check made to see if the current user has that role.

The role claim type is expressed using the following URI: ""

So instead of using the RoleManager, you can "add a user to a role" from the UserManager, doing something like this:

var um = new UserManager();
um.AddClaimAsync(1, new Claim("", "administrator"));

With the above lines you have added a role claim with the value "administrator" to the user with the id "1"...

Claims authorization, as suggested by MSFT, can simplify and increase the performance of authentication and authorization processes eliminating some back-end queries every time authorization takes place.

Using Claims you may not need the RoleStore anymore. (AspNetRoles, AspNetUserRoles)

How should I multiple insert multiple records?

You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications

If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

Change a Git remote HEAD to point to something besides master

First, create the new branch you would like to set as your default, for example:

$>git branch main

Next, push that branch to the origin:

$>git push origin main

Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."

Then, if you so choose, you can delete the master branch:

$>git push origin :master

List of All Locales and Their Short Codes?

If you are using php-intl to localize your application, you probably want to use ResourceBundle::getLocales() instead of static list that you maintain yourself. It can also give you locales for particular language.


/* Output might show
  * Array
  * (
  *    [0] => af
  *    [1] => af_NA
  *    [2] => af_ZA
  *    [3] => am
  *    [4] => am_ET
  *    [5] => ar
  *    [6] => ar_AE
  *    [7] => ar_BH
  *    [8] => ar_DZ
  *    [9] => ar_EG
  *    [10] => ar_IQ
  *  ...

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    temp_buf = (char *) malloc(5 * 1024);



Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

DNS problem, nslookup works, ping doesn't

I think the problem can be because of the NAT. Normally the DNS clients make requests via UDP. But when the DNS server is behind the NAT the UDP requests will not work.

Change the column label? e.g.: change column "A" to column "Name"

I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:

First, insert a new row at the beginning of the sheet. Within that row, define the names you need: new row

Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now: new top row

Now whenever you scroll down in the document, the first row will be "pinned" to the top: new behaviour

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

What's the difference between event.stopPropagation and event.preventDefault?

 alert("parent click event fired !");_x000D_
<script src=""></script>_x000D_
<div id="foo">_x000D_
  <button id="but">button</button>_x000D_

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Try this

Check this How do i get the gmt time in php

echo date("Y-m-d H:i:s", time()); 

Slack URL to open a channel from browser

Referencing a channel within a conversation

To create a clickable reference to a channel in a Slack conversation, just type # followed by the channel name. For example: #general.

# mention of a channel

To grab a link to a channel through the Slack UI

To share the channel URL externally, you can grab its link by control-clicking (Mac) or right-clicking (Windows) on the channel name:

grabbing a channel's URL

The link would look like this:

Note that this link doesn't change even if you change the name of the channel. So, it is better to use this link rather than the one based on channel's name.

To compose a URL for a channel based on channel name<channel_name>

Opening the above URL from a browser would launch the Slack client (if available) or open the slack channel on the browser itself.

To compose a URL for a direct message (DM) channel to a user<username>

Str_replace for multiple items

    array("replace", "items"),

Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

PHP - Check if two arrays are equal

Try serialize. This will check nested subarrays as well.

$foo =serialize($array_foo);
$bar =serialize($array_bar);
if ($foo == $bar) echo "Foo and bar are equal";

How to read integer values from text file

use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

       E.I_EmpName AS EMPNAME,
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
               ' ',
               '') AS WORKDATE,
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 WHERE E.I_EMPID <> '22'

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

Using the last-child selector

As an alternative to using a class you could use a detailed list, setting the child dt elements to have one style and the child dd elements to have another. Your example would become:

#refundReasonMenu #nav li:dd
  border-bottom: 1px solid #b5b5b5;


<div id="refundReasonMenu">
  <dl id="nav">
        <dt><a id="abc" href="#">abcde</a></dt>
        <dd><a id="def" href="#">xyz</a></dd>

Neither method is better than the other and it is just down to personal preference.

Convert a string representation of a hex dump to a byte array using Java?

For Me this was the solution, HEX="FF01" then split to FF(255) and 01(01)

private static byte[] BytesEncode(String encoded) {
    byte result[] = new byte[encoded.length() / 2];
    char enc[] = encoded.toUpperCase().toCharArray();
    String curr = "";
    for (int i = 0; i < encoded.length(); i=i+2) {
        curr = encoded.substring(i,i+2);
            result[i]=((byte) Integer.parseInt(curr, 16));
            result[i/2]=((byte) Integer.parseInt(curr, 16));

    return result;

Problems with jQuery getJSON using local files in Chrome

An additional way to get around the problem is by leveraging Flash Player's Local Only security sandbox and ExternalInterface methods. One can have JavaScript request a Flash application published using the Local Only security sandbox to load the file from the hard drive, and Flash can pass the data back to JavaScript via Flash's ExternalInterface class. I've tested this in Chrome, FF and IE9, and it works well. I'd be happy to share the code if anyone is interested.

EDIT: I've started a google code (ironic?) project for the implementation:

Difference between .on('click') vs .click()

$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });
  1. it is more effective then $('.UPDATE').click(function(){ });
  2. it can use less memory and work for dynamically added elements.
  3. some time dynamic fetched data with edit and delete button not generate JQuery event at time of EDIT OR DELETE DATA of row data in form, that time $(document).on('click','.UPDATE',function(){ }); is effectively work like same fetched data by using jquery. button not working at time of update or delete:

enter image description here

Using NotNull Annotation in method argument

SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);

Excel VBA code to copy a specific string to clipboard

To write text to (or read text from) the Windows clipboard use this VBA function:

Function Clipboard$(Optional s$)
    Dim v: v = s  'Cast to variant for 64-bit VBA support
    With CreateObject("htmlfile")
    With .parentWindow.clipboardData
        Select Case True
            Case Len(s): .setData "text", v
            Case Else:   Clipboard = .getData("text")
        End Select
    End With
    End With
End Function

'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123

'To read text from the clipboard:
MsgBox Clipboard

This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.

How do I URl encode something in Node.js?

Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")

If you don't want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))

Why are static variables considered evil?

Summarising few basic Advantages & Disadvantages of using Static methods in Java:


  1. Globally accessible i.e. not tied with any particular object instance.
  2. One instance per JVM.
  3. Can be accessed by using class name (No object require).
  4. Contains a single value applicable to all instances.
  5. Load up on JVM startup and dies when JVM shuts down.
  6. They doesn't modify state of Object.


  1. Static members are always part of memory whether they are in use or not.
  2. You can not control creation and destruction of static variable. Usefully they have been created at program loading and destroyed when program unload (or when JVM shuts down).
  3. You can make statics thread safe using synchronize but you need some extra efforts.
  4. If one thread change value of a static variable that can possibly break functionality of other threads.
  5. You must know “static“ before using it.
  6. You cannot override static methods.
  7. Serialization doesn't work well with them.
  8. They don't participate in runtime polymorphism.
  9. There is a memory issue (to some extent but not much I guess) if a large number of static variables/methods are used. Because they will not be Garbage Collected until program ends.
  10. Static methods are hard to test too.

Matplotlib figure facecolor (background color)

I had to use the transparent keyword to get the color I chose with my initial


like this:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)

Only exception being are you sure your Autofill code is perfect...

How to style a disabled checkbox?

You can't style a disabled checkbox directly because it's controlled by the browser / OS.

However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.

I've thrown up a basic example so that you can see it in action:

Here's the sample:

input[type="checkbox"] {_x000D_
    display: none;_x000D_
label:before {_x000D_
    background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
    border: 1px solid #035f8f;_x000D_
    height: 36px;_x000D_
    width: 36px;_x000D_
    display: block;_x000D_
    cursor: pointer;_x000D_
input[type="checkbox"] + label:before {_x000D_
    content: '';_x000D_
    background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
    border-color: #3d9000;_x000D_
    color: #96be0a;_x000D_
    font-size: 38px;_x000D_
    line-height: 35px;_x000D_
    text-align: center;_x000D_
input[type="checkbox"]:disabled + label:before {_x000D_
    border-color: #eee;_x000D_
    color: #ccc;_x000D_
    background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
    content: '?';_x000D_
<div><input id="cb1" type="checkbox" disabled checked /><label for="cb1"></label></div>_x000D_
<div><input id="cb2" type="checkbox" disabled /><label for="cb2"></label></div>_x000D_
<div><input id="cb3" type="checkbox" checked /><label for="cb3"></label></div>_x000D_
<div><input id="cb4" type="checkbox" /><label for="cb4"></label></div>

Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

Node.js: how to consume SOAP XML web service

Adding to Kim .J's solution: you can add preserveWhitespace=true in order to avoid a Whitespace error. Like this:


Using parameters in batch files at Windows command line

Use variables i.e. the .BAT variables and called %0 to %9

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

How generate unique Integers based on GUIDs

I had a requirement where multiple instances of a console application needed to get an unique integer ID. It is used to identify the instance and assigned at startup. Because the .exe is started by hands, I settled on a solution using the ticks of the start time.

My reasoning was that it would be nearly impossible for the user to start two .exe in the same millisecond. This behavior is deterministic: if you have a collision, you know that the problem was that two instances were started at the same time. Methods depending on hashcode, GUID or random numbers might fail in unpredictable ways.

I set the date to 0001-01-01, add the current time and divide the ticks by 10000 (because I don't set the microseconds) to get a number that is small enough to fit into an integer.

 var now = DateTime.Now;
 var zeroDate = DateTime.MinValue.AddHours(now.Hour).AddMinutes(now.Minute).AddSeconds(now.Second).AddMilliseconds(now.Millisecond);
 int uniqueId = (int)(zeroDate.Ticks / 10000);

EDIT: There are some caveats. To make collisions unlikely, make sure that:

  • The instances are started manually (more than one millisecond apart)
  • The ID is generated once per instance, at startup
  • The ID must only be unique in regard to other instances that are currently running
  • Only a small number of IDs will ever be needed

SQL: Two select statements in one query

Using union will help in this case.

You can also use join on a condition that always returns true and is not related to data in these tables.See below

select tmd .name,tbc.goals from tblMadrid tmd join tblBarcelona tbc on 1=1;

MySQL error 2006: mysql server has gone away

This error happens basically for two reasons.

  1. You have a too low RAM.
  2. The database connection is closed when you try to connect.

You can try this code below.

# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()
    except (AttributeError, MySQLdb.OperationalError):
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()

It mitigates the error whatever the reason behind it, especially for the second reason.

If it's caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.

Using multiple delimiters in awk

If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t directly, you could set the output separator and it will be included automatically:

< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'


@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.

Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]; i.e. it was an array object.

Normally, the next steps to solving a problem like this are:

  • examining the stacktrace to figure out which line of which class threw the exception,
  • examining the corresponding source code, to see what the expected type, and
  • tracing back to see where the object with the "wrong" type came from.

"UnboundLocalError: local variable referenced before assignment" after an if statement

Contributing to ferrix example,

class Battery():

    def __init__(self, battery_size = 60):
        self.battery_size = battery_size
    def get_range(self):
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
        range = 270

        message = "This car can go approx " + str(range)
        message += "Fully charge"

My message will not execute, because none of my conditions are fulfill therefore receiving " UnboundLocalError: local variable 'range' referenced before assignment"

def get_range(self):
    if self.battery_size <= 70:
        range = 240
    elif self.battery_size >= 85:
        range = 270

Access a function variable outside the function without using "global"

I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.

    # just an example 
    def func(): # define a function
       func.y = 4 # here y is a local variable, which I want to access; func.y defines 
                  # a method for my example function which will allow me to access 
                  # function's local variable y
       x = func.y + 8 # this is the main task for the function: what it should do
       return x

    func() # now I'm calling the function
    a = func.y # I put it's local variable into my new variable
    print(a) # and print my new variable

Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"

In Rails 3.x this is the way to specify the table name.

How do I see if Wi-Fi is connected on Android?

I am using this in my apps to check if the active network is Wi-Fi:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI)

    // Do your work here


How can I capitalize the first letter of each word in a string?

Capitalize string with non-uniform spaces

I would like to add to @Amit Gupta's point of non-uniform spaces:

From the original question, we would like to capitalize every word in the string s = 'the brown fox'. What if the string was s = 'the brown fox' with non-uniform spaces.

def solve(s):
    # If you want to maintain the spaces in the string, s = 'the brown      fox'
    # Use s.split(' ') instead of s.split().
    # s.split() returns ['the', 'brown', 'fox']
    # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
    capitalized_word_list = [word.capitalize() for word in s.split(' ')]
    return ' '.join(capitalized_word_list)

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#


MVC (old one)

MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)

MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP) enter image description here

Another image: enter image description here

notifyDataSetChange not working from custom adapter

Add this code

runOnUiThread(new Runnable() { public void run() {
               adapter = new CustomAdapter(anotherdata);

Use find command but exclude files in two directories

Try something like

find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)

and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.

Android Fragment no view found for ID?

I had the same issue but my issue was happenning on orientation change. None of the other solutions worked. So it turns out that I forgot to remove setRetainInstance(true); from my fragments, when doing a two or one pane layout based on screen size.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);

Then you enumerate all stored credentials by calling


Then you go over the results.

Firefox setting to enable cross domain Ajax request

To allow cross domain:

  1. enter about:config
  2. accept to be careful
  3. enter security.fileuri.strict_origin_policy in the search bar
  4. change to false

You can now close the tab. Normally you can now make cross domain request with this config.

See here for more details.

How the int.TryParse actually works

Just because int.TryParse gives you the value doesn't mean you need to keep it; you can quite happily do this:

int temp;
if (int.TryParse(inputString, out temp))
    // do stuff

You can ignore temp entirely if you don't need it. If you do need it, then hey, it's waiting for you when you want it.

As for the internals, as far as I remember it attempts to read the raw bytes of the string as an int and tests whether the result is valid, or something; it's not as simple as iterating through looking for non-numeric characters.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb version/

    Replace with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9


    gpg --hkp://keyserver --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
  3. Install the new version

     sudo apt-get install r-base-dev
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

index.php not loading by default

This one works like a charm!


<IfModule dir_module>
    DirectoryIndex index.html
     DirectoryIndex index.php

then after that from

<Files ".ht*">
    Require all denied


 <Files ".ht*">
    Require all granted

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL


Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

When you want to return a JSON response in MVC .Net Core You can also use:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().

Where can I get a virtual machine online?

Try this:

one year free. I do use this for a while.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

private void removeGroupsFromUsers() {
    for (User u : users) {

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

How to center an element in the middle of the browser window?

you can center any object in viewport, here is an example using jquery


$(window).on("resize", function() {

function posicionar(elemento){
    var altoDocumento = $(window).height();//alto
    var anchoDocumento = $(window).width();
    var centroXDocumento = anchoDocumento / 2;
    var centroYDocumento = altoDocumento / 2;
    var altoElemento = $(elemento).outerHeight(true);//ancho real del elemento
    var anchoElemento = $(elemento).outerWidth(true);//alto 

    var centroXElemento = anchoElemento / 2;// centro x del elemento
    var centroYElemento = altoElemento / 2; // centro y del elemento

    var posicionXElemento = centroXDocumento - centroXElemento;
    var posicionYElemento = centroYDocumento - centroYElemento;

    $(elemento).css("top", posicionYElemento);
    $(elemento).css("left", posicionXElemento);

the html

<div id="midiv"></div>

Note: you must execute the function onDomReady and when the window resizes.

here is de jsfiddle

Select and display only duplicate records in MySQL

This works the fastest for me

    primary_key NOT IN (
        GROUP BY
            COUNT(*) = 1

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.

Here is the example for :

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:


Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.

The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)

Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

changing minDate option in JQuery DatePicker not working

Use minDate as string:

$('#datePickerId').datepicker({minDate: '0'});

This would set today as minimum selectable date .

Increment value in mysql update query

You should use PDO to prevent SQL injection risk.

You can connect to DB like this :

try {
    $bdd = new PDO('mysql:host=xxxx;dbname=xxxx', 'user', 'password', $pdo_options);
    $bdd->query('SET NAMES "utf8"');
} catch (PDOException $e) {

No need to query DB to get the number of points. You can increment directly in the update query (points = points + 1).

(note : Also, it’s not a good idea to increment the value with PHP because you need to select first the data and the value can changed if other users are updated it.)

$req = $bdd->prepare('UPDATE member_profile SET 
            points = points + 1
            WHERE user_id = :user_id');

    'user_id' => $userid

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

What is the difference between Views and Materialized Views in Oracle?

A view uses a query to pull data from the underlying tables.

A materialized view is a table on disk that contains the result set of a query.

Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.

Unable to create Genymotion Virtual Device

Disadvantage of deleting the deployed and .ova files is obvious i.e. you have to download the massive 200mb image again. A better choice is to :

  • Open genymotion and open settings --> virtualBox --> virtual devices browse and set the path to a folder which can be completely accessed without administrative pivileges e.g. for ubuntu set virtual devices path to any folder in your home directory for example /home/user/deployed and for windows you can use a folder like C://deployed.

That's it . Now you can use your already existing .ova file again to deploy image to new locatioin without any problem.

text box input height

You can define a class or id for input fields.


input {
    line-height: 20px;

Hope this helps you.

Read data from a text file using Java

String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    // Uncomment the line below if you want to skip the fist line (e.g if headers)
    // line = br.readLine();

    while ((line = br.readLine()) != null) {

        // do something with line


} catch (IOException e) {
    System.out.println("ERROR: unable to read file " + file);

How do you create different variable names while in a loop?

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    if break_condition == True:

How do I pretty-print existing JSON data with Java?

Use gson.

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);


  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [

Has anyone ever got a remote JMX JConsole to work?

After putting my Google-fu to the test for the last couple of days, I was finally able to get this to work after compiling answers from Stack Overflow and this page

Reposting from the Dell Boomi page:

To Enable Remote JMX on an Atom

If you want to monitor the status of an Atom, you need to turn on Remote JMX (Java Management Extensions) for the Atom.

Use a text editor to open the <atom_installation_directory>\bin\atom.vmoptions file.

Add the following lines to the file:

The one line that I haven't seen any Stack Overflow answer cover is

In my case, I was attempting to retrieve Kakfa metrics, so I simply changed the above option to match the value. So, without authentication of any kind, the bare minimum config should look like this: remote port) remote port)
-Djava.rmi.server.hostname=(CNAME|IP Address)

Position: absolute and parent height?

Here is my workaround,
In your example you can add a third element with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:


   <div class="one"></div>
   <div class="two"></div>
   <div class="three"></div>


    height: 30px;
    z-index: -1;
    visibility: hidden;

How can I split a string with a string delimiter?

You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.

You can also use regular expression. A simple google search turned out with this

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {

call a static method inside a class?

In the later PHP version self::staticMethod(); also will not work. It will throw the strict standard error.

In this case, we can create object of same class and call by object

here is the example

class Foo {

    public function fun1() {
        echo 'non-static';   

    public static function fun2() {
        echo (new self)->fun1();

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.


Check this SO question that explains how to do it.

How to check file MIME type with javascript before upload?

As stated in other answers, you can check the mime type by checking the signature of the file in the first bytes of the file.

But what other answers are doing is loading the entire file in memory in order to check the signature, which is very wasteful and could easily freeze your browser if you select a big file by accident or not.

 * Load the mime type based on the signature of the first bytes of the file_x000D_
 * @param  {File}   file        A instance of File_x000D_
 * @param  {Function} callback  Callback with the result_x000D_
 * @author Victor www.vitim.us_x000D_
 * @date   2017-03-23_x000D_
function loadMime(file, callback) {_x000D_
    //List of known mimes_x000D_
    var mimes = [_x000D_
            mime: 'image/jpeg',_x000D_
            pattern: [0xFF, 0xD8, 0xFF],_x000D_
            mask: [0xFF, 0xFF, 0xFF],_x000D_
            mime: 'image/png',_x000D_
            pattern: [0x89, 0x50, 0x4E, 0x47],_x000D_
            mask: [0xFF, 0xFF, 0xFF, 0xFF],_x000D_
        // you can expand this list @see
    function check(bytes, mime) {_x000D_
        for (var i = 0, l = mime.mask.length; i < l; ++i) {_x000D_
            if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {_x000D_
                return false;_x000D_
        return true;_x000D_
    var blob = file.slice(0, 4); //read the first 4 bytes of the file_x000D_
    var reader = new FileReader();_x000D_
    reader.onloadend = function(e) {_x000D_
        if ( === FileReader.DONE) {_x000D_
            var bytes = new Uint8Array(;_x000D_
            for (var i=0, l = mimes.length; i<l; ++i) {_x000D_
                if (check(bytes, mimes[i])) return callback("Mime: " + mimes[i].mime + " <br> Browser:" + file.type);_x000D_
            return callback("Mime: unknown <br> Browser:" + file.type);_x000D_
//when selecting a file on the input_x000D_
fileInput.onchange = function() {_x000D_
    loadMime(fileInput.files[0], function(mime) {_x000D_
        //print the output to the screen_x000D_
        output.innerHTML = mime;_x000D_
<input type="file" id="fileInput">_x000D_
<div id="output"></div>

java how to use classes in other package?

It should be like import package_name.Class_Name --> If you want to import a specific class (or)

import package_name.* --> To import all classes in a package

Create intermediate folders if one doesn't exist

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:


Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).


Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:


You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.


Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
        bDate = True
        bValue = True
        bChanged = False
        Dim sVal As String
        Dim dDate As Date
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
        sVal = CStr(inData.Value)
        dDate = Now()
        Set wb = inData.Worksheet.Parent
        Set dProps = wb.CustomDocumentProperties
    On Error Resume Next
        Set pValue = dProps.Item(sName)
        If Err.Number <> 0 Then
            bValue = False
        End If
    On Error GoTo 0
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    On Error Resume Next
        Set pDate = dProps.Item(sNameDate)
        If Err.Number <> 0 Then
            bDate = False
        End If
    On Error GoTo 0
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
        If bChanged Then
            pDate.Value = dDate
            dDate = pDate.Value
        End If
        UDF_Date = dDate
     End Function

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

Spring Data and Native Query with pagination

Removing \n#pageable\n from both query and count query worked for me. Springboot version : 2.1.5.RELEASE DB : Mysql

How to validate numeric values which may contain dots or commas?


\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.

How to create a readonly textbox in ASP.NET MVC3 Razor

The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:

  1. Razor code before changes

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
  2. After changes

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)

Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.

How to pass a list from Python, by Jinja2 to JavaScript

To add up on the selected answer, I have been testing a new option that is working too using jinja2 and flask:

def my_view():
    data = [1, 2, 3, 4, 5]
    return render_template('index.html', data=data)

The template:

    console.log( {{ data | tojson }} )

the output of the rendered template:

    console.log( [1, 2, 3, 4] )

The safe could be added but as well like {{ data | tojson | safe }} to avoid html escape but it is working without too.

Cast a Double Variable to Decimal

Convert.ToDecimal(the double you are trying to convert);

git ignore vim temporary files

Vim temporary files end with ~ so you can add to the file .gitignore the line


Vim also creates swap files that have the swp and swo extensions. to remove those use the lines:


This will ignore all the vim temporary files in a single project

If you want to do it globally, you can create a .gitignore file in your home (you can give it other name or location), and use the following command:

git config --global core.excludesfile ~/.gitignore

Then you just need to add the files you want to ignore to that file

How do I create a link to add an entry to a calendar?

You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.

I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.

Format an Excel column (or cell) as Text in C#?

Solution that worked for me for Excel Interop:

myWorksheet.Columns[j].NumberFormat = "@";      // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "@"; // cell as a text

This code should run before putting data to Excel. Column and row numbers are 1-based.

A bit more details. Whereas accepted response with reference for SpreadsheetGear looks almost correct, I had two concerns about it:

  1. I am not using SpreadsheetGear. I was interested in regular Excel communication thru Excel interop without any 3rdparty libraries,
  2. I was searching for the way to format column by number, not using ranges like "A:A".

How do you check if a JavaScript Object is a DOM Object?

if you are using jQuery, try this

$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false

"No resource identifier found for attribute 'showAsAction' in package 'android'"

If you are building with Eclipse, make sure your project's build target is set to Honeycomb too.

Taking screenshot on Emulator from Android Studio

Click on the Monitor (DDMS Included) button on the toolbar -- it looks like the Android bugdroid:

IDE window showing Monitor button

That will bring up the DDMS window. Select the emulator instance from the Devices tab on the left, and click on the camera button in the toolbar above it, next to the stop sign icon:

Monitor window

Note that if your emulator is running Android 4.4 or I think 4.3, then screen capture functionality is broken -- you'll have to use a physical device to get screenshots on those OS versions. It works okay for Android prior to 4.3. That bug is

CSS hide scroll bar, but have element scrollable

Similar to Kiloumap L'artélon's answer,

::-webkit-scrollbar {

works too

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

After a lot of searching this worked for me:

public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source, 
                                                    string orderByProperty, bool desc)
    string command = desc ? "OrderByDescending" : "OrderBy";
    var type = typeof(TEntity);
    var property = type.GetProperty(orderByProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExpression = Expression.Lambda(propertyAccess, parameter);
    var resultExpression = Expression.Call(typeof(Queryable), command, 
                                           new[] { type, property.PropertyType },
    return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression);

What is the difference between range and xrange functions in Python 2.X?

xrange uses an iterator (generates values on the fly), range returns a list.

How to do SVN Update on my project using the command line

From the command line it would be just:

svn update

(in the directory you've got a copy of a SVN project).

Change size of axes title and labels in ggplot2

I think a better way to do this is to change the base_size argument. It will increase the text sizes consistently.

g + theme_grey(base_size = 22)

As seen here.

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

How do I format a number with commas in T-SQL?

`/* Author: Tsiridis Dimitris */
/* Greek amount format. For the other change the change on replace of '.' & ',' */
CREATE FUNCTION dbo.formatAmount  (
@amtIn as varchar(20)
) RETURNS varchar(20)

return cast(REPLACE(SUBSTRING(CONVERT(varchar(20), CAST(@amtIn AS money), 1),1,
LEN(CONVERT(varchar(20), CAST(@amtIn AS money), 1))-3), ',','.')
 + replace(RIGHT(CONVERT(varchar(20), CAST(@amtIn AS money), 1),3), '.',',') AS VARCHAR(20))


SELECT [geniki].[dbo].[formatAmount]('9888777666555.44')`

Run an Ansible task only when the variable contains a specific string

If variable1 is a string, and you are searching for a substring in it, this should work:

when: '"value" in variable1'

if variable1 is an array or dict instead, in will search for the exact string as one of its items.

How to Remove Array Element and Then Re-Index Array?

In addition to xzyfer's answer

The function

function custom_unset(&$array=array(), $key=0) {

        // remove item at index

        // 'reindex' array
        $array = array_values($array);

        //$array = array_merge($array); 

    return $array;



custom_unset($my_array, 1);


 array(2) {
    string(5) "test0"
    string(5) "test2"

DataGrid get selected rows' column values

I believe the reason there's no straightforward property to access the selected row of a WPF DataGrid is because a DataGrid's selection mode can be set to either the row-level or the cell-level. Therefore, the selection-related properties and events are all written against cell-level selection - you'll always have selected cells regardless of the grid's selection mode, but you aren't guaranteed to have a selected row.

I don't know precisely what you're trying to achieve by handling the CellEditEnding event, but to get the values of all selected cells when you select a row, take a look at handling the SelectedCellsChanged event, instead. Especially note the remarks in that article:

You can handle the SelectedCellsChanged event to be notified when the collection of selected cells is changed. If the selection includes full rows, the Selector.SelectionChanged event is also raised.

You can retrieve the AddedCells and RemovedCells from the SelectedCellsChangedEventArgs in the event handler.

Hope that helps put you on the right track. :)

var.replace is not a function

Replace wouldn't replace numbers. It replaces strings only.

This should work.

function trim(str) {
    return str.toString().replace(/^\s+|\s+$/g,'');

If you only want to trim the string. You can simply use "str.trim()"

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:


    echo "<p>Logged in as ".$user."</p>";
    echo "Please log in.";

How the same problem can be solved with an API centric approach by outputting JSON like this:


  user: {
      username: 'Joe', 
      securityToken: 'secret'

and in Angular you could do a get, and handle the response client side.

$"", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

This usually happens when the version of one of the DLLs of the testing environment does not match the development environment.

Clean and Build your solution and take all your DLLs to the environment where the error is happening that should fix it

Retrieve all values from HashMap keys in an ArrayList Java

Put i++ somewhere at the end of your loop.

In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.

FYI: the below is doing a redundant search:

   date_value[i] = map.get(keys[i]);              
} else if(keys[i].equals(VALUE)){              
   value_values[i] = map.get(keys[i]);             

replace with

   date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){              
   value_values[i] = mapping.getValue()

Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

How do I handle ImeOptions' done button click?

While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:


You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.

It was, however, the attribute imeOptions="actionUnspecified" that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions. You can specify a "Send" button or "Next" button. The full list can be found here.

With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListener for the EditText element. As in your example:

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
       //do here your stuff f
       return true;
    return false;

Now in my example I had android:imeOptions="actionUnspecified" attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:

    mPasswordView = (EditText) findViewById(;
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == || id == EditorInfo.IME_NULL) {
                return true;
            return false;

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});


#loading-img {
    background: url( center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;

And a demo with animated image.

What does "'') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

PHP pass variable to include

You can execute all in "second.php" adding variable with jQuery

<div id="first"></div>

$("#first").load("second.php?a=<?php echo $var?>")

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)

enter image description here

What are alternatives to document.write?

Here is code that should replace document.write in-place:

    var scripts = document.getElementsByTagName('script');
    var lastScript = scripts[scripts.length-1];
    lastScript.insertAdjacentHTML("beforebegin", s);

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:

Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.

Similarly for download: How to schedule an automatic FTP download on Windows?

WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)

Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

What is the simplest way to convert array to vector?

Personally, I quite like the C++2011 approach because it neither requires you to use sizeof() nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):

#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));

Obviously, with C++2011 you might want to use initializer lists anyway:

std::vector<int> v({ 1, 2, 3, 4, 5 });

Relative path to absolute path in C#?

Assuming you know the real directory the XML file lives in use Path.Combine, e.g.

var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");

If you want to get back the full path with any ..'s collapsed then you can use:

Path.GetFullPath((new Uri(absolute_path)).LocalPath);

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Depending on what you actually want to achieve, you should take a look at Android Handlers:

If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).

Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

How to write to the Output window in Visual Studio?

OutputDebugString function will do it.

example code

    void CClass::Output(const char* szFormat, ...)
    char szBuff[1024];
    va_list arg;
    va_start(arg, szFormat);
    _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);


jQuery animated number counter from zero to value

this inside the step callback isn't the element but the object passed to animate()

$('.Count').each(function (_, self) {
        Counter: 0
        Counter: $(self).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function () {

Another way to do this and keep the references to this would be

$('.Count').each(function () {
        Counter: $(this).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function (now) {


Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

<span myd1="">directive template1</span>

Second result:

<div myd2=""><span>directive template2</span></div>

Core Data: Quickest way to delete all instances of an entity

In Swift 2.0:

func deleteAllData(entity: String)
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

        let results = try managedContext.executeFetchRequest(fetchRequest)
        for managedObject in results
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
    } catch let error as NSError {
        print("Detele all data in \(entity) error : \(error) \(error.userInfo)")

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

There's actually a way to do this without javascript.

If you set an <input>'s required selector to true, you can check if there's text in it with the CSS :valid tag.


MDN Docs
CSS Tricks

input {
  background: red;

input:valid {
  background: lightgreen;
<input type="text" required>

How to run a function in jquery

I would do it this way:

(function($) {
jQuery.fn.doSomething = function() {
   return this.each(function() {
      var $this = $(this);

      $ {
         // Your function goes here

Then on document ready you can do stuff like this:

$(document).ready(function() {

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

How to "set a breakpoint in malloc_error_break to debug"

I solve it by close safari inspector. Refer to my post. I also found sound sometimes when I run my app for testing, then I open safari with auto inspector on, after this, I do some action in my app then this issue triggered.

enter image description here

How do I measure execution time of a command on the Windows command line?

I'm using Windows XP and for some reason timeit.exe does not work for me. I found another alternative - PTIME. This works very well.

Example -

C:\> ptime

ptime 1.0 for Win32, Freeware -
Copyright(C) 2002, Jem Berkes <[email protected]>

Syntax: ptime command [arguments ...]

ptime will run the specified command and measure the execution time
(run time) in seconds, accurate to 5 millisecond or better. It is an
automatic process timer, or program timer.

C:\> ptime cd

ptime 1.0 for Win32, Freeware -
Copyright(C) 2002, Jem Berkes <[email protected]>

===  cd ===

Execution time: 0.015 s

Exit codes in Python

There is an errno module that defines standard exit codes:

For example, Permission denied is error code 13:

import errno, sys

if can_access_resource():

Making a mocked method return an argument that was passed to it

I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:

public class RoomService {
    public Room findByName(String roomName) {...}
    public void persist(Room room) {...}

The service mock uses a map to store the Room instances.

RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();

// mock for method persist
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            Room room = (Room) arguments[0];
            roomMap.put(room.getName(), room);
        return null;

// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
    public Room answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            String key = (String) arguments[0];
            if (roomMap.containsKey(key)) {
                return roomMap.get(key);
        return null;

We can now run our tests on this mock. For example:

String name = "room";
Room room = new Room(name);
assertThat(roomService.findByName(name), equalTo(room));

Rails 4 LIKE query - ActiveRecord adds quotes


 def, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'

See the docs on AREL conditions for more info.

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.

So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.

How to conclude your merge of a file?

I just did:

git merge --continue

At which point vi launched to edit a merge comment. A quick :wq and the merge was done.

Gradients in Internet Explorer 9

Opera will soon start having builds available with gradient support, as well as other CSS features.

The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.

Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.

I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.

This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?

Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)

Fit image to table cell [Pure HTML]

if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

<img align="center" width="100%" height="100%" src="" />

see the fiddle :

but still it better to handling this with CSS, i suggest you that.

  • I hope this help.

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

How to dynamically add a style for text-align using jQuery

I usually use


Hope that helps

Storyboard - refer to ViewController in AppDelegate

    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
    self.window.rootViewController = [storyboard instantiateInitialViewController];

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access from AND from, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.


When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

|- Mans
|- MansTest
   |- SoftLib
      |- Soft
         |- SoftWork
      |- Unittests

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in, the documented solution to that is to add to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in", that's now how imports work. If you want to import Soft.SoftLib in, you have to setup to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in")
    print("foo call module1 from manModules: " + module1())

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
    from ...Mans import man1
  File "/temp/man/Mans/", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between and The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test ( to be importing stuff from under the test folder (MansTest).

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:


%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call


Twitter Search doc link:

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.


d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)


d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Returning a file to View/Download in ASP.NET MVC

If, like me, you've come to this topic via Razor components as you're learning Blazor, then you'll find you need to think a little more outside of the box to solve this problem. It's a bit of a minefield if (also like me) Blazor is your first forray into the MVC-type world, as the documentation isn't as helpful for such 'menial' tasks.

So, at the time of writing, you cannot achieve this using vanilla Blazor/Razor without embedding an MVC controller to handle the file download part an example of which is as below:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

public class FileHandlingController : ControllerBase
    public FileContentResult Download(int attachmentId)
        TaskAttachment taskFile = null;

        if (attachmentId > 0)
            // taskFile = <your code to get the file>
            // which assumes it's an object with relevant properties as required below

            if (taskFile != null)
                var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                    FileNameStar = taskFile.Filename

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());

        return new FileContentResult(taskFile?.FileData, taskFile?.FileContentType);

Next, make sure your application startup (Startup.cs) is configured to correctly use MVC and has the following line present (add it if not):


.. and then finally modify your component to link to the controller, for example (iterative based example using a custom class):

        @foreach (var attachment in yourAttachments)
            <td><a href="api/[email protected]" target="_blank">@attachment.Filename</a> </td>
            <td>@attachment.Created?.ToString("dd MMM yyyy")</td>
            <td><ul><li class="oi oi-circle-x delete-attachment"></li></ul></td>

Hopefully this helps anyone who struggled (like me!) to get an appropriate answer to this seemingly simple question in the realms of Blazor…!

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13

How to select option in drop down protractorjs e2e tests

We wanted to use the elegant solution up there using angularjs material but it didnt work because there are actually no option / md-option tags in the DOM until the md-select has been clicked. So the "elegant" way didn't work for us (note angular material!) Here is what we did for it instead, don't know if its the best way but its definately working now

element.all(by.css('md-select')).each(function (eachElement, index) {;                    // select the <select>
    browser.driver.sleep(500);              // wait for the renderings to take effect
    element(by.css('md-option')).click();   // select the first md-option
    browser.driver.sleep(500);              // wait for the renderings to take effect

We needed to have 4 selects selected and while the select is open, there is an overlay in the way of selecting the next select. thats why we need to wait 500ms to make sure we don't get into trouble with the material effects still being in action.

How can I run a php without a web server?

For windows system you should be able to run php by following below steps:

  1. Download php version you want to use and put it in c:\php.
  2. append ;c:\php to your system path using cmd or gui.
  3. call $ php -S localhost:8000 command in a folder which you want to serve the pages from.

How to initialize struct?

Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

Is it safe to clean docker/overlay2/

I recently had a similar issue, overlay2 grew bigger and bigger, But I couldn’t figure out what consumed the bulk of the space.

df showed me that overlay2 was about 24GB in size.

With du I tried to figure out what occupied the space… and failed.

The difference came from the fact that deleted files (mostly log files in my case) where still being used by a process (Docker). Thus the file doesn’t show up with du but the space it occupies will show with df.

A reboot of the host machine helped. Restarting the docker container would probably have helped already… This article on helped me to figure that out.

How do I call a JavaScript function on page load?

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

let ignoreFirstChange = 0;_x000D_
let observer = (new MutationObserver((m, ob)=>_x000D_
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());_x000D_
)).observe(content, {childList: true, subtree:true });_x000D_
// TEST: simulate element loading_x000D_
let tmp=1;_x000D_
function loadContent(name) {  _x000D_
    console.log(`Element ${name} loaded`)_x000D_
    content.innerHTML += `<div>My name is ${name}</div>`; _x000D_
}; _x000D_
<div id="content"><div>

Pandas DataFrame to List of Lists

Maybe something changed but this gave back a list of ndarrays which did what I needed.


How to include bootstrap css and js in reactjs app?

I try with instruction:

npm install bootstrap
npm install jquery popper.js

then in src/index.js:

import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
import Popper from 'popper.js';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Dropdown />, document.getElementById('root'));

Twitter bootstrap collapse: change display of toggle button

My following JS solution is better than the other approaches here because it ensures that it will always say 'open' when the target is closed, and vice versa.


<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">
<div class="collapse" id="collapseExample">
  <div class="well">


$('[data-toggle-secondary]').each(function() {
    var $toggle = $(this);
    var originalText = $toggle.text();
    var secondaryText = $'toggle-secondary');
    var $target = $($toggle.attr('href'));

    $target.on('', function() {
        if ($toggle.text() == originalText) {
        } else {


$('[data-toggle-secondary]').each(function() {_x000D_
    var $toggle = $(this);_x000D_
    var originalText = $toggle.text();_x000D_
    var secondaryText = $'toggle-secondary');_x000D_
    var $target = $($toggle.attr('href'));_x000D_
    $target.on('', function() {_x000D_
        if ($toggle.text() == originalText) {_x000D_
        } else {_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<script src=""></script>_x000D_
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">_x000D_
<div class="collapse" id="collapseExample">_x000D_
  <div class="well">_x000D_

JS Fiddle

Other benefits of this approach:

  • the code is DRY and reusable
  • each collapse button stays separate
  • you only need to put one change into the HTML: adding the data-toggle-secondary attribute

Is there an equivalent to background-size: cover and contain for image elements?

There is actually quite a simple css solution which even works on IE8:

.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  /* Width and height can be anything. */_x000D_
  width: 50vw;_x000D_
  height: 50vh;_x000D_
img {_x000D_
  position: absolute;_x000D_
  /* Position the image in the middle of its container. */_x000D_
  top: -9999px;_x000D_
  right: -9999px;_x000D_
  bottom: -9999px;_x000D_
  left: -9999px;_x000D_
  margin: auto;_x000D_
  /* The following values determine the exact image behaviour. */_x000D_
  /* You can simulate background-size: cover/contain/etc._x000D_
     by changing between min/max/standard width/height values._x000D_
     These values simulate background-size: cover_x000D_
  min-width: 100%;_x000D_
  min-height: 100%;_x000D_
<div class="container">_x000D_
    <img src="" alt="" />_x000D_

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  @include media-breakpoint-only(lg) {
    column-count: 4;
  @include media-breakpoint-only(md) {
    column-count: 3;
  @include media-breakpoint-only(sm) {
    column-count: 2;

SASS Demo:

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;

CSS-only Demo:

How to programmatically set drawableLeft on Android button?

Following is the way to change the color of the left icon in edit text and set it in left side.

 Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);

int color = ContextCompat.getColor(this, R.color.blackColor);

    DrawableCompat.setTint(img, color);

} else {
    img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);

JavaScript: How to find out if the user browser is Chrome?

  isAndroid: /Android/.test(navigator.userAgent),_x000D_
  isCordova: !!window.cordova,_x000D_
  isEdge: /Edge/.test(navigator.userAgent),_x000D_
  isFirefox: /Firefox/.test(navigator.userAgent),_x000D_
  isChrome: /Google Inc/.test(navigator.vendor),_x000D_
  isChromeIOS: /CriOS/.test(navigator.userAgent),_x000D_
  isChromiumBased: !! && !/Edge/.test(navigator.userAgent),_x000D_
  isIE: /Trident/.test(navigator.userAgent),_x000D_
  isIOS: /(iPhone|iPad|iPod)/.test(navigator.platform),_x000D_
  isOpera: /OPR/.test(navigator.userAgent),_x000D_
  isSafari: /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent),_x000D_
  isTouchScreen: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,_x000D_
  isWebComponentsSupported: 'registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template')_x000D_
}, null, '  '));

How to check the exit status using an if statement

Just to add to the helpful and detailed answer:

If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:

(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }

Or, use a case statement:

run_some_command; ec=$?  # grab the exit code into a variable so that it can
                         # be reused later, without the fear of being overwritten
case $ec in
    0) ;;
    1) printf '%s\n' "Command exited with non-zero"; exit 1;;
    *) do_something_else;;

Related answer about error handling in Bash:

How do I get whole and fractional parts from double in JSP/Java?

Since Java 8, you can use Math.floorDiv.

It returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient.

Some examples:

floorDiv(4, 3) == 1
floorDiv(-4, 3) == -2

Alternatively, the / operator can be used:

(4 / 3) == 1
(-4 / 3) == -1


PHP/regex: How to get the string value of HTML tag?

this might be old but my answer might help someone

You can simply use

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
echo strip_tags($str);

Hashcode and Equals for Hashset

Because in 2nd case you adding same reference twice and HashSet have check against this in HashMap.put() on which HashSet is based:

        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            return oldValue;

As you can see, equals will be called only if hash of key being added equals to the key already present in set and references of these two are different.

Delete all the records

When the table is very large, it's better to delete table itself with drop table TableName and recreate it, if one has create table query; rather than deleting records one by one, using delete from statement because that can be time consuming.

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

How do you log content of a JSON object in Node.js?

function prettyJSON(obj) {
    console.log(JSON.stringify(obj, null, 2));

// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level

JSON.stringify on MDN

Is it possible to have a default parameter for a mysql stored procedure?

No, this is not supported in MySQL stored routine syntax.

Feel free to submit a feature request at

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>

Check the fiddle here and the screenshot below.

enter image description here

Here is the solution:

    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>

How to rename a file using svn?

It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:

$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

Eclipse, regular expression search and replace

NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is

search: (\w+\\.someMethod\\(\\))

replace: ((TypeName)$1)


In search:

  • First and last (, ) depicts a group in regex

  • \w depicts words (alphanumeric + underscore)

  • + depicts one or more (ie one or more of alphanumeric + underscore)

  • . is a special character which depicts any character (ie .+ means one or more of any character). Because this is a special character to depict a . we should give an escape character with it, ie \.

  • someMethod is given as it is to be searched.

  • The two parenthesis (, ) are given along with escape character because they are special character which are used to depict a group (we will discuss about group in next point)

In replace:

  • It is given ((TypeName)$1), here $1 depicts the group. That is all the characters that are enclosed within the first and last parenthesis (, ) in the search field

  • Also make sure you have checked the 'Regular expression' option in find an replace box

ImportError: No module named 'pygame'

I ran into the error a few days ago! Thankfully, I found the answer.

You see, the problem is that pygame comes in a .whl (wheel) file/package. So, as a result, you have to pip install it.

Pip installing is a very tricky process, so please be careful. The steps are:-

Step1. Go to C:/Python (whatever version you are using)/Scripts. Scroll down. If you see a file named pip.exe, then that means that you are in the right folder. Copy the path.

Step2. In your computer, search for Environment Variables. You should see an option labeled 'Edit the System Environment Variables'. Click on it.

Step3. There, you should see a dialogue box appear. Click 'Environment Variables'. Click on 'Path'. Then, click 'New'. Paste the path that you copies earlier.

Step4. Click 'Ok'.

Step5. Shift + Right Click wherever your pygame is installed. Select 'Open Command Window Here' from the dropdown menu. Type in 'pip install py' then click tab and the full file name should fill in. Then, press Enter, and you're ready to go! Now you shouldn't get the error again!!!

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

You can use regex.findall():

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

How to convert text to binary code in JavaScript?

Thank you Majid Laissi for your answer

I made 2 functions out from your code:

the goal was to implement convertation of string to VARBINARY, BINARY and back

const stringToBinary = function(string, maxBytes) {
  //for BINARY maxBytes = 255
  //for VARBINARY maxBytes = 65535
  let binaryOutput = '';
  if (string.length > maxBytes) {
    string = string.substring(0, maxBytes);

  for (var i = 0; i < string.length; i++) {
    binaryOutput += string[i].charCodeAt(0).toString(2) + ' ';

  return binaryOutput;

and backward convertation:

const binaryToString = function(binary) {
  const arrayOfBytes = binary.split(' ');

  let stringOutput = '';

  for (let i = 0; i < arrayOfBytes.length; i++) {
    stringOutput += String.fromCharCode(parseInt(arrayOfBytes[i], 2));

  return stringOutput;

and here is a working example:,console

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I had the same problem with System.Web.Http.WebHost, Version= being referenced but the latest NuGet package was I edited the web.config files, re-installed the NuGet package, then edited the visual studio project files for all of my projects to make sure no references to persisted. Even after all this, the problem persisted.

Then I looked in the bin folder for the project that was throwing the exception, where I found a DLL for one of my other projects that is not a dependency and should never have been there. I deleted the offending DLL (which had been compiled using the version of System.Web.Http.WebHost), rebuilt the troublesome project, and now it is working.

copy-item With Alternate Credentials

Bringing this back from the dead again. I got around a similar credentials problem by wrapping the .ps1 in a batch file and doing the Win7, Shift + r.Click RunAs. If you wanted to, you can also use PsExec thus:

psexec.exe /accepteula /h /u user /p pwd cmd /c "echo. | powershell.exe -File script.ps1"

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

What could cause java.lang.reflect.InvocationTargetException?

You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.

Just unwrap the cause within the InvocationTargetException and you'll get to the original one.

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

    container_name: mysql
    image: mysql:latest
    restart: always
     - "3306:3306"

    container_name: apigw-tomcat
    build: tomcat/.
     - "8080:8080"
     - "8009:8009"
     - mysql

    driver: bridge
       - subnet:

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")


How do I count unique items in field in Access query?

Try this

SELECT Count(*) AS N

Read this for more info.

Search code inside a Github project

Go here: and enter "pattern repo:user_name/repo_name".

For example, to search for cnn_learner in the fastai repo of user fastai, enter this:

cnn_learner repo:fastai/fastai

That's it. The only annoyance is you'll need an extra click. It will tell you:

We couldn’t find any repositories matching 'cnn_learner repo:fastai/fastai'

because by default it searches for repositories matching that search string...

So just click on the left on "Code" and it will display what you want.

Or get the code search results directly with a URL like this:

Kubernetes service external ip pending

There are three types of exposing your service Nodeport ClusterIP LoadBalancer

When we use a loadbalancer we basically ask our cloud provider to give us a dns which can be accessed online Note not a domain name but a dns.

So loadbalancer type does not work in our local minikube env.

jQuery - passing value from one input to another

Assuming you can put ID's on the inputs:

$('#name').change(function() {

JSFiddle Example

Otherwise you'll have to select using the names:

$('input[name="name"]').change(function() {

recursion versus iteration

Most of the answers seem to assume that iterative = for loop. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.

All (computable) functions can be implemented both recursively and using while loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.

What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).

Change the "From:" address in Unix "mail"

Thanks BEAU

mail -s "Subject" [email protected] -- -f [email protected]

I just found this and it works for me. The man pages for mail 8.1 on CentOS 5 doesn't mention this. For -f option, the man page says:

-f Read messages from the file named by the file operand instead of the system mailbox. (See also folder.) If no file operand is specified, read messages from mbox instead of the system mailbox.

So anyway this is great to find, thanks.