Programs & Examples On #Imagebutton

An image button is a button that displays an image, regardless of platform

How to add image for button in android?

Simply use ImageButton View and set image for it:`

    android:src="@android:drawable/ic_menu_search" />

How to set transparent background for Image Button in code?

simply use this in your imagebutton layout






doesn't give perfect transparency

ImageButton in Android

You can also set background is transparent. So the button looks like fit your icon.

    android:src="@drawable/eye" />

jQuery UI Dialog - missing close icon

This is a comment on the top answer, but I felt it was worth its own answer because it helped me answer the problem.

If you want to keep Bootstrap declared after JQuery UI (I did because I wanted to use the Bootstrap tooltip), declaring the following (I declared it after $(document).ready) will allow the button to appear again (answer from

var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton            // give $().bootstrapBtn the Bootstrap functionality

Android ImageButton with a selected state?

The best way to do this without more images :

public static void buttonEffect(View button){
    button.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                case MotionEvent.ACTION_UP: {
            return false;

How to have a transparent ImageButton: Android

Try using null for the background ...


How to pass multiple values through command argument in

You can try this:

CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'

How to show the text on a ImageButton?

Best way to show Text on button(with image)

example of text on button with image background

Your Question: How to show text on imagebutton?

Answer: You can not display text with imageButton. Method that tell in Accepted answer also not work.


If you use android:drawableLeft="@drawable/buttonok" then you can not set drawable in center of button.

If you use android:background="@drawable/button_bg" then color of your drawable will be changed.

In android world there are thousands of option to do this. But here i provide best alternate according to my point of view. (see below)

Solution: Use cardView with LinearLayout

Your drawable/image use in LinearLayout because it shows in center. And with help of textView you can set text on this. We makes cardView background to transparent.


                        android:text="Happy Coding"


here i explain some terms:

app:cardBackgroundColor="@android:color/transparent" for make transparent background of cardView

app:cardElevation="0dp" for hide evelation lines around cardView

app:cardUseCompatPadding="true" its provide actual size of cardView. Always use this when you use cardView

set your image/drawable in LinearLayout as a background.

Sorry, for my Bad English.

Happy Coding:)

Fit Image in ImageButton in Android

I recently found out by accident that since you have more control on a ImageView that you can set an onclicklistener for an image here is a sample of a dynamically created image button

private int id;
private bitmap bmp;
    LinearLayout.LayoutParams familyimagelayout = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT );

    final ImageView familyimage = new ImageView(this);
            familyimage.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    //what you want to do put here

Android Imagebutton change Image OnClick

You have assing button to your imgButton variable:

public void onCreate(Bundle savedInstanceState) {

    imgButton = (Button) findViewById(;

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
    rep.DataSource = reader;
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

How to make Python script run as service?

I offer two recommendations:


1) Install the supervisor package (more verbose instructions here):

sudo apt-get install supervisor

2) Create a config file for your daemon at /etc/supervisor/conf.d/flashpolicyd.conf:


3) Restart supervisor to load your new .conf

supervisorctl update
supervisorctl restart flashpolicyd

systemd (if currently used by your Linux distro)

Description=My Python daemon

ExecStart=/usr/bin/python3 /opt/project/


Place this file into /etc/systemd/system/my_daemon.service and enable it using systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block.

To view logs:

systemctl status my_daemon

Removing items from a ListBox in

If you only want to clear the list box, you should use the Clear (winforms | wpf | method:


RadioGroup: How to check programmatically

I prefer to use

RadioButton b = (RadioButton) findViewById(;

instead of using the accepted answer.

RadioButton b = (RadioButton) findViewById(;

The reason is setChecked(true) only changes the checked state of radio button. It does not trigger the onClick() method added to your radio button. Sometimes this might waste your time to debug why the action related to onClick() not working.

Permission denied at hdfs

I've solved this problem by using following steps

su hdfs
hadoop fs -put /usr/local/input-data/ /input

How to split a long array into smaller arrays, with JavaScript

const originalArr = [1,2,3,4,5,6,7,8,9,10,11];
const splittedArray = [];
  while (originalArr.length > 0) {

output for range 3

splittedArray === [[1,2,3][4,5,6][7,8,9][10,11]]

output for range 4

splittedArray === [[1,2,3,4][5,6,7,8][9,10,11]]

Python reading from a file and saving to utf-8

You can also get through it by the code below:


How can I select all elements without a given class in jQuery?

if (!$(row).hasClass("changed")) {
    // do your stuff

How to get jQuery to wait until an effect is finished?

With jQuery 1.6 version you can use the .promise() method.

    // will be called when all the animations on the queue finish

How to compile .c file with OpenSSL includes?

You need to include the library path (-L/usr/local/lib/)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

It works for me.

How to open a new file in vim in a new window

I use this subtle alias:

alias vim='gnome-terminal -- vim'

-x is deprecated now. We need to use -- instead

jQuery find element by data attribute value

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

$(function() {_x000D_
.active {_x000D_
  background: green;_x000D_
<script src=""></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Is it better in C++ to pass by value or pass by constant reference?

Simple difference :- In function we have input and output parameter , so if your passing input and out parameter is same then use call by reference else if input and output parameter are different then better to use call by value .

example void amount(int account , int deposit , int total )

input parameter : account , deposit output paramteter: total

input and out is different use call by vaule

  1. void amount(int total , int deposit )

input total deposit output total

python date of the previous month

For someone who got here and looking to get both the first and last day of the previous month:

from datetime import date, timedelta

last_day_of_prev_month = - timedelta(days=1)

start_day_of_prev_month = - timedelta(

# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)


First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28

What does "The APR based Apache Tomcat Native library was not found" mean?

Installation the native library on Ubuntu server with:

sudo apt-get install libtcnative-1

If that does not work tomcat-native needs to be installed

  1. Install Oracle java7:

    • sudo add-apt-repository ppa:webupd8team/java
    • sudo apt-get update
    • sudo apt-get install oracle-java7-installer
    • sudo apt-get install oracle-java7-set-default
  2. Install tomcat apr:

  3. Install tomcat tomcat-native:

Push existing project into Github

If you're on a Mac (and this probably works the same on a PC), here's a very easy way to do this. Strangely enough I've looked high and low for this simple process and never found it.

  • Do not do anything on Github (other than having an account, and not having used up all your available repos).
  • Download GitHub for Mac and install. Go through the account setup, etc. Do NOT create any repositories for your existing project.
  • "Add New Local Repository" in repositories.
  • Select your existing folder. It'll ask if you want to do that, say yes.
  • Once done, you'll see a list of all your files, etc. Commit them.
  • Go to Repositories and Publish (this will create the new repo on GitHub for you, if you set up your account properly).
  • Go to Repositories and Push (you'll either see the "nothing to push" thing, or it'll push your files/changes to the newly-auto-made repo).
    • Wonder why you could not find this simple process anywhere else.

I know it is not recommended to use the project folder as the repo folder. I do it all the time, it always works, it makes it simple, and I never have any trouble with it.

how can I Update top 100 records in sql server

Note, the parentheses are required for UPDATE statements:

update top (100) table1 set field1 = 1

Open links in new window using AngularJS

you can use:

$, windowName, attributes);

Copy table without copying data



so the keys and indexes are copied over as, well.

Documentation Received fatal alert: protocol_version

Not sure if you found an answer but I had this problem and needed to upgrade TLS version to 1.2

private HttpsURLConnection getSSlConnection(String url, String username, String password){
    SSLContext sc = SSLContext.getInstance("TLSv1.2")
    // Create a trust manager that accepts all SSL sites
    TrustManager[] trustAllCerts = new TrustManager[1]
    def tm = new X509TrustManager(){
        public void checkClientTrusted(X509Certificate[] certs, String authType) {

        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0]
    trustAllCerts[0] = tm

    sc.init(null, trustAllCerts, new SecureRandom())
    HttpsURLConnection connection = (HttpsURLConnection) getConnection(url, username, password)
    return connection

How to check if a date is in a given range?

$startDatedt = strtotime($start_date)
$endDatedt = strtotime($end_date)
$usrDatedt = strtotime($date_from_user)

if( $usrDatedt >= $startDatedt && $usrDatedt <= $endDatedt)
   //..falls within range

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

How do I connect to mongodb with node.js (and authenticate)?

You can do it like this

var db = require('mongo-lite').connect('mongodb://localhost/test')

more details ...

Python Function to test ping

It looks like you want the return keyword

def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
        pingstatus = "Network Error"

    return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n

Some info on python functions:

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating and

Connection string with relative path to the database file

   <?xml version="1.0"?>  
    <!--FailIfMissing=false -->  
    <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>  

How to show form input fields based on select value?

I got its answer. Here is my code

<label for="db">Choose type</label>
<select name="dbType" id=dbType">
   <option>Choose Database Type</option>
   <option value="oracle">Oracle</option>
   <option value="mssql">MS SQL</option>
   <option value="mysql">MySQL</option>
   <option value="other">Other</option>

<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>

And my script is

$(function() {

        $('#dbType').change(function() {
            $('#' + $(this).val()).slideDown("slow");

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

How to make a local variable (inside a function) global

You could use module scope. Say you have a module called utils:

f_value = 'foo'

def f():
    return f_value

f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:

>> import utils
>> utils.f()
>> utils.f_value = 'bar'
>> utils.f()

Note that you can import the function by name:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()

But not the attribute:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()

This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

Set focus on textbox in WPF

In Code behind you can achieve it only by doing this.

 private void Window_Loaded(object sender, RoutedEventArgs e)
            txtIndex.Focusable = true;

Note: It wont work before window is loaded

Spacing between elements

It depends on what exactly you want to accomplish. Let's assume you have this structure:

<p style="width:400px;">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.

If you want the space between the single lines to be bigger, you should increase


If you want the space at the end to be bigger, you should increase


If you want the space at the end to be bigger, but have the background fill the space (or the border around the space) use


Of course, there are also the corresponding values for space on the top:


Some examples:

<p style="line-height: 30px; width: 300px; border: 1px solid black;">
     Space between single lines 
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
<p style="margin-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
<p style="padding-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border

here you can see this code in action:

Of course you should put your styles in a separate stylesheet, the inline code was just to show the effect.

here you have a little schematic demonstration of what which value affects:

           content                 +
                                   |      padding-bottom
                  <----------------+      +
           content                        |    border-bottom
                                          |    +
                                          |    |
        +-------------+<------------------+    |       margin-bottom
                                               |       +
     +===================+ <-------------------+       |
  +-------------------------+ <------------------------+

No submodule mapping found in .gitmodule for a path that's not a submodule

I just hit this error after trying to "git submodule init" on a new checkout of my repo. Turns out I had specified the module sub-folder with the wrong case initially. Since I'm on a Mac with a case-sensitive filesystem (hurr) it was failing. For example:

git submodule add [email protected]:user/project.git MyApp/Resources/Project
Cloning into 'MyApp/Resources/Project'

succeeds but the trouble is that on disk the path is


What I don't understand is why git is init'ing the module to wrong folder (ignoring the incorrect case in my command) but then operating correctly (by failing) with subsequent commands.

Android: remove notification from notification bar

A short one Liner of this is:


Or to cancel all notifications is:


Made for AndroidX or Support Libraries.

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

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

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

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug


Visual studio's error is :

"The process cannot access the file 'bin\Debug**app.exe**' because it is being used by another process."

So ,go to task manager of windows(Ctrl+Shift+Esc),find your application name and force it to close by Endprocces.

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

If nothing else works, make sure that you have correct permissions and ownership set up during building. A quick fix can be:

sudo chown -R <you>:<your_group> *
sudo chmod -R 755 *

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See


from the command prompt for more information.

How to load up CSS files using Javascript?

Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

function loadStyle(src) {
    return new Promise(function (resolve, reject) {
        let link = document.createElement('link');
        link.href = src;
        link.rel = 'stylesheet';

        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`Style load error for ${src}`));


You can implement it as follows:

window.onload = function () {
        .then(() => loadStyle("css/style.css"))
        .then(() => loadStyle("css/icomoon.css"))
        .then(() => {
            alert('All styles are loaded!');
        }).catch(err => alert(err));

It's really cool, right? This is a way to decide the priority of the styles using Promises.

To see a multi-style loading implementation see:

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

How to install Python packages from the tar.gz file without using pip install

If you don't wanted to use PIP install atall, then you could do the following:

1) Download the package 2) Use 7 zip for unzipping tar files. ( Use 7 zip again until you see a folder by the name of the package you are looking for. Ex: wordcloud)

Folder by Name 'wordcloud'

3) Locate Python library folder where python is installed and paste the 'WordCloud' folder itself there

Python Library folder

4) Success !! Now you can import the library and start using the package.

enter image description here

How to clear APC cache entries?

If you want to monitor the results via json, you can use this kind of script:


$result1 = apc_clear_cache();
$result2 = apc_clear_cache('user');
$result3 = apc_clear_cache('opcode');
$infos = apc_cache_info();
$infos['apc_clear_cache'] = $result1;
$infos["apc_clear_cache('user')"] = $result2;
$infos["apc_clear_cache('opcode')"] = $result3;
$infos["success"] = $result1 && $result2 && $result3;
header('Content-type: application/json');
echo json_encode($infos);

As mentioned in other answers, this script will have to be called via http or curl and you will have to be secured if it is exposed in the web root of your application. (by ip, token...)

Why cannot change checkbox color whatever I do?

Agree with iLoveTux , applying too many things (many colors and backgrounds) nothing worked , but here's what started working, Apply these properties to its css:

-webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;

and then css styling started working on checkbox :)

SQL Server : Columns to Rows

I needed a solution to convert columns to rows in Microsoft SQL Server, without knowing the colum names (used in trigger) and without dynamic sql (dynamic sql is too slow for use in a trigger).

I finally found this solution, which works fine:

    attr.insRow.value('local-name(.)', 'nvarchar(128)') as FieldName,
    attr.insRow.value('.', 'nvarchar(max)') as FieldValue 
FROM ( Select      
          i.ID as PK,
          i.LastModifiedBy as Username,
          convert(xml, (select i.* for xml raw)) as insRowCol
       FROM inserted as i
     ) as insRowTbl
CROSS APPLY insRowTbl.insRowCol.nodes('/row/@*') as attr(insRow)

As you can see, I convert the row into XML (Subquery select i,* for xml raw, this converts all columns into one xml column)

Then I CROSS APPLY a function to each XML attribute of this column, so that I get one row per attribute.

Overall, this converts columns into rows, without knowing the column names and without using dynamic sql. It is fast enough for my purpose.

(Edit: I just saw Roman Pekar answer above, who is doing the same. I used the dynamic sql trigger with cursors first, which was 10 to 100 times slower than this solution, but maybe it was caused by the cursor, not by the dynamic sql. Anyway, this solution is very simple an universal, so its definitively an option).

I am leaving this comment at this place, because I want to reference this explanation in my post about the full audit trigger, that you can find here:

Producing a new line in XSLT

You can use: <xsl:text>&#10;</xsl:text>

see the example

<xsl:variable name="module-info">
  <xsl:value-of select="@name" /> = <xsl:value-of select="@rev" />

if you write this in file e.g.

<redirect:write file="temp.prop" append="true">
  <xsl:value-of select="$module-info" />

this variable will produce a new line infile as:

commons-dbcp_commons-dbcp = 1.2.2
junit_junit = 4.4
org.easymock_easymock = 2.4

How do you follow an HTTP Redirect in Node.js?

Make another request based on response.headers.location:

      const request = function(url) {
        lib.get(url, (response) => {
          var body = [];
          if (response.statusCode == 302) {
            body = [];
          } else {
            response.on("data", /*...*/);
            response.on("end", /*...*/);
        } ).on("error", /*...*/);

How to run function in AngularJS controller on document ready?

The answer

    function() { 
        $timeout(function() {
            //do something

is the only one that works in most scenarios I tested. In a sample page with 4 components all of which build HTML from a template, the order of events was

$document ready
(and these 3 were repeated 3 more times in the same order for the other 3 components)
$viewContentLoaded (repeated 3 more times)
$timeout execution (repeated 3 more times)

So a $document.ready() is useless in most cases since the DOM being constructed in angular may be nowhere near ready.

But more interesting, even after $viewContentLoaded fired, the element of interest still could not be found.

Only after the $timeout executed was it found. Note that even though the $timeout was a value of 0, nearly 200 milliseconds elapsed before it executed, indicating that this thread was held off for quite a while, presumably while the DOM had angular templates added on a main thread. The total time from the first $document.ready() to the last $timeout execution was nearly 500 milliseconds.

In one extraordinary case where the value of a component was set and then the text() value was changed later in the $timeout, the $timeout value had to be increased until it worked (even though the element could be found during the $timeout). Something async within the 3rd party component caused a value to take precedence over the text until sufficient time passed. Another possibility is $scope.$evalAsync, but was not tried.

I am still looking for that one event that tells me the DOM has completely settled down and can be manipulated so that all cases work. So far an arbitrary timeout value is necessary, meaning at best this is a kludge that may not work on a slow browser. I have not tried JQuery options like liveQuery and publish/subscribe which may work, but certainly aren't pure angular.

Setting a width and height on an A tag

You can also use display: inline-block. The advantage of this is that it will set the height and width like a block element but also set it inline so that you can have another a tag sitting right next to it, permitting the parent space.

You can find out more about display properties here

How to pretty print XML from Java?

Just another solution which works for us

import org.dom4j.DocumentHelper;

 * Pretty Print XML String
 * @param inputXmlString
 * @return
public static String prettyPrintXml(String xml) {

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
    catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    return sw.toString();

Java 8 Lambda function that throws exception?

You can use unthrow wrapper

Function<String, Integer> func1 = s -> Unthrow.wrap(() -> myMethod(s));


Function<String, Integer> func2 = s1 -> Unthrow.wrap((s2) -> myMethod(s2), s1);

How to append rows to an R data frame


Not knowing what you are trying to do, I'll share one more suggestion: Preallocate vectors of the type you want for each column, insert values into those vectors, and then, at the end, create your data.frame.

Continuing with Julian's f3 (a preallocated data.frame) as the fastest option so far, defined as:

# pre-allocate space
f3 <- function(n){
  df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
  for(i in 1:n){
    df$x[i] <- i
    df$y[i] <- toString(i)

Here's a similar approach, but one where the data.frame is created as the last step.

# Use preallocated vectors
f4 <- function(n) {
  x <- numeric(n)
  y <- character(n)
  for (i in 1:n) {
    x[i] <- i
    y[i] <- i
  data.frame(x, y, stringsAsFactors=FALSE)

microbenchmark from the "microbenchmark" package will give us more comprehensive insight than system.time:

microbenchmark(f1(1000), f3(1000), f4(1000), times = 5)
# Unit: milliseconds
#      expr         min          lq      median         uq         max neval
#  f1(1000) 1024.539618 1029.693877 1045.972666 1055.25931 1112.769176     5
#  f3(1000)  149.417636  150.529011  150.827393  151.02230  160.637845     5
#  f4(1000)    7.872647    7.892395    7.901151    7.95077    8.049581     5

f1() (the approach below) is incredibly inefficient because of how often it calls data.frame and because growing objects that way is generally slow in R. f3() is much improved due to preallocation, but the data.frame structure itself might be part of the bottleneck here. f4() tries to bypass that bottleneck without compromising the approach you want to take.

Original answer

This is really not a good idea, but if you wanted to do it this way, I guess you can try:

for (i in 1:10) {
  df <- rbind(df, data.frame(x = i, y = toString(i)))

Note that in your code, there is one other problem:

  • You should use stringsAsFactors if you want the characters to not get converted to factors. Use: df = data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)

div hover background-color change?

div hover background color change

Try like this:


How do I parse a HTML page with Node.js

You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.

Other options include:

  • BeautifulSoup for python
  • you can convert you html to xhtml and use XSLT
  • HTMLAgilityPack for .NET
  • CsQuery for .NET (my new favorite)
  • The spidermonkey and rhino JS engines have native E4X support. This may be useful, only if you convert your html to xhtml.

Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

There are a bunch of good solutions here but I'd suggest going the other route with this. If searching is the most important thing and the 'secret' property is not used on the view at all; my approach for this would be to use the built-in angular filter with all its benefits and simply map the model to a new array of objects.

Example from the question:

$scope.people = { 
                              return { 

Now, in html simply use the regular filter to search both these properties.

<div ng-repeat="member in people | filter: searchString">

Commenting code in Notepad++

This link was exactly what I was searching for .

Let me summarize the answers for others' benefit (for python and notepad++)

1) Ctrl+K on multiple lines (i.e. selected region) allows you to block comment.

Also note that pressing the combination multiple times allows you to add multiple "#"s (sometimes I use that while testing to differentiate from other comments)

2) Ctrl+Shift+K (on the commented region) allows you to perform block uncomment

3) Ctrl+Shift+K on an uncommented selected region does not comment it

4) Ctrl+Q allows you to block comment/uncomment in a toggled mode (meaning, you cannot add multiple '#'s like in 1) )

Hope this helps another wandering soul.

Question - how would you develop a hack of keyboard combinations to comment/uncomment if there were no shortcuts? Just curious. I've no clue hence asking.

java.lang.IllegalStateException: Fragment not attached to Activity

this happen when the fragment does not have a context ,thus the getActivity()method return null. check if you use the context before you get it,or if the Activity is not exist anymore . use context in fragment.onCreate and after api response usually case this problem

Count specific character occurrences in a string


Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

I used strin as variant to handle very long text. The split can be zero-based or one-based for low end depending on user settings, and subtracting it ensures the correct count.

I did not include a test for strcount being longer than strin to keep code concise.

IPython Notebook save location

To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.

set "var=%cd%"
cd var
ipython notebook

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

SOLUTION OF Regsvr32: DllRegisterServer entry point was not found,

  1. Go to systemdrive(generally c:)\system32 and search file "Regsvr32.exe"
  2. Right click and click in properties and go to security tab and click in advanced button.
  3. Click in owner tab and click edit and select administrators and click ok.
  4. Click in permissions
  5. Click in change permissions.
  6. Choose administrators and click edit and put tick on full control and click ok.
  7. Similarly, choose SYSTEM and edit and put tick on full control and click ok and click in other dialog box which are opened.
  8. Now .dll files can be registered and error don't come, you should re-install any software whose dll files was not registered during installation.

Moment JS start and end of given month

var d = new moment();
var startMonth = d.clone().startOf('month');
var endMonth = d.clone().endOf('month');
console.log(startMonth, endMonth);


HTML table with 100% width, with vertical scroll inside tbody

I got it finally right with pure CSS by following these instructions:

The first step is to set the <tbody> to display: block so an overflow and height can be applied. From there the rows in the <thead> need to be set to position: relative and display: block so that they’ll sit on top of the now scrollable <tbody>.

tbody, thead { display: block; overflow-y: auto; }

Because the <thead> is relatively positioned each table cell needs an explicit width

td:nth-child(1), th:nth-child(1) { width: 100px; }
td:nth-child(2), th:nth-child(2) { width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

But unfortunately that is not enough. When a scrollbar is present browsers allocate space for it, therefore, the <tbody> ends up having less space available than the <thead>. Notice the slight misalignment this creates...

The only workaround I could come up with was to set a min-width on all columns except the last one.

td:nth-child(1), th:nth-child(1) { min-width: 100px; }
td:nth-child(2), th:nth-child(2) { min-width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

Whole codepen example below:


.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
.fixed_headers th {
  text-decoration: underline;
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
.fixed_headers thead {
  background-color: #333333;
  color: #fdfdfd;
.fixed_headers thead tr {
  display: block;
  position: relative;
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
.fixed_headers tbody tr:nth-child(even) {
  background-color: #dddddd;
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
.old_ie_wrapper tbody {
  height: auto;


<!-- IE < 10 does not like giving a tbody a height.  The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">

<table class="fixed_headers">
      <td>These are red.</td>
      <td>These are green.</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
      <td>These are orange.</td>
      <td>These are yellow.</td>
      <td>These are green.</td>
      <td>These are Purple</td>
      <td>These are red.</td>
      <td>These are red.</td>
      <td>These are red.</td>
      <td>These are orange inside.</td>
      <td>These are green inside.</td>
      <td>These are green.</td>
      <td>These are red.</td>
      <td>These are blue.</td>
      <td>These are orange.</td>
      <td>Passion Fruit</td>
      <td>These are green.</td>

<!--[if lte IE 9]>

EDIT: Alternative solution for table width 100% (above actually is for fixed width and didn't answer the question):


      <td>These are red.</td>
      <td>These are green.</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
      <td>These are orange.</td>
      <td>These are yellow.</td>
      <td>These are green.</td>


table {
  width: 100%;
  text-align: left;
  min-width: 610px;
tr {
  height: 30px;
  padding-top: 10px
tbody { 
  height: 150px; 
  overflow-y: auto;
  overflow-x: hidden;
th,td,tr,thead,tbody { display: block; }
td,th { float: left; }
th:nth-child(1) {
  width: 20%;
th:nth-child(2) {
  width: 20%;
  float: left;
th:nth-child(3) {
  width: 59%;
  float: left;
/* some colors */
thead {
  background-color: #333333;
  color: #fdfdfd;
table tbody tr:nth-child(even) {
  background-color: #dddddd;


How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If you have completed all steps given by Surjeet and still not getting network connection icon then follow below steps:

  1. Unpair Device using right click on the device from the Connected section.

    enter image description here

  2. Reconnect the device.

  3. Click on "+" button from the end of the lefthand side of the popup.

enter image description here

  1. Select the device and click on next button

enter image description here

  1. Click on Trust and passcode(if available) from the device.

enter image description here

  1. Click on Done button.

enter image description here

  1. Now, click on connect via network.

enter image description here

Now you can see the network connection icon after the device name. Enjoy!

enter image description here

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);

You can see an explanation of how it works here.

How to find and return a duplicate value in array

Alas most of the answers are O(n^2).

Here is an O(n) solution,

a = %w{the quick brown fox jumps over the lazy dog}
h =
a.find { |each| (h[each] += 1) == 2 } # => 'the"

What is the complexity of this?

  • Runs in O(n) and breaks on first match
  • Uses O(n) memory, but only the minimal amount

Now, depending on how frequent duplicates are in your array these runtimes might actually become even better. For example if the array of size O(n) has been sampled from a population of k << n different elements only the complexity for both runtime and space becomes O(k), however it is more likely that the original poster is validating input and wants to make sure there are no duplicates. In that case both runtime and memory complexity O(n) since we expect the elements to have no repetitions for the majority of inputs.

MySQL: Insert record if not exists in table

This query can be used in PHP code.

I have an ID column in this table, so I need check for duplication for all columns except this ID column:

#need to change values
SET @goodsType = 1, @sybType=5, @deviceId = asdf12345SDFasdf2345;    

INSERT INTO `devices` (`goodsTypeId`, `goodsId`, `deviceId`) #need to change tablename and columnsnames
SELECT * FROM (SELECT @goodsType, @sybType, @deviceId) AS tmp
    SELECT 'goodsTypeId' FROM `devices` #need to change tablename and columns names
    WHERE `goodsTypeId` = @goodsType
        AND `goodsId` = @sybType
        AND `deviceId` = @deviceId
) LIMIT 1;

and now new item will be added only in case of there is not exist row with values configured in SET string

How to convert local time string to UTC?

I'm having good luck with dateutil (which is widely recommended on SO for other related questions):

from datetime import *
from dateutil import *
from import *

# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()

# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in local time zone since 
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')

(Code was derived from this answer to Convert UTC datetime string to local datetime)

How to create an array for JSON using PHP?

also for array you can use short annotattion:

$arr = [
        "region" => "valore",
        "price" => "valore2"
        "region" => "valore",
        "price" => "valore2"
        "region" => "valore",
        "price" => "valore2"

echo json_encode($arr);

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 


P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

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


    $conn = mysqli_connect('localhost','root','','northwind');
    $data_per_page = 10;
    $select = "SELECT * FROM `customers`";  
    $select_run = mysqli_query($conn, $select);
    $records = mysqli_num_rows($select_run);
    // while ($result = mysqli_fetch_array($select_run)) {      
    //     echo $result['CompanyName'] . '<br>';        
    // }
    // $records;
    echo "<br>";
    $no_of_page = ceil($records / $data_per_page);
        $page = 1;
        $page = $_GET['page'];
    $page_limit_data = ($page - 1) * 10;
    $select = "SELECT * FROM customers LIMIT " . $page_limit_data . ',' . $data_per_page ;
    $select_run = mysqli_query($conn, $select);
    while ($row_select = mysqli_fetch_array($select_run)){
        echo $row_select['CompanyName'] . '<br>' ;
    for($page=1; $page<= $no_of_page; $page++){ 
        echo "<a href='pagination.php?page=$page'> $page" . ', ';   
<h1> Testing Limit Functions Here  </h1>
$limit = "SELECT CompanyName From customers LIMIT 10 OFFSET 5";
$limit_run = mysqli_query($conn , $limit);
while($limit_result = mysqli_fetch_array($limit_run)){
    echo $limit_result['CompanyName'] . '<br>';

To get total number of columns in a table in sql

It can be done using:-


Download files in laravel using Response::download

While using laravel 5 use this code as you don`t need headers.

return response()->download($pathToFile); .

If you are using Fileentry you can use below function for downloading.

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    return response()->download($pathToFile);           

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Best Java obfuscator?

As said elsewhere on here, proguard is good, but what might not be known is that there is also a third-party maven plugin for it here've used them both together and they're very good.

Use jquery to set value of div tag

To put text, use .text('text')

If you want to use .html(SomeValue), SomeValue should have html tags that can be inside a div it must work too.

Just check your script location, as farzad said.

Reference: .html and text

MySQL command line client for Windows

If you are looking for tools like the the mysql and mysqldump command line client for Windows for versions around mysql Ver 14.14 Distrib 5.6.13, for Win32 (x86) it seems to be in HOMEDRIVE:\Program Files (x86)\MySQL\MySQL Workbench version

This directory is also not placed in the path by default so you will need to add it to your PATH environment variable before you can easily run it from the command prompt.

Also, there is a mysql utilities console but it does not work for my needs. Below is a list of the capabilities on the mysql utilities console in case it works for you:

Utility           Description
----------------  ---------------------------------------------------------
mysqlauditadmin   audit log maintenance utility
mysqlauditgrep    audit log search utility
mysqldbcompare    compare databases for consistency
mysqldbcopy       copy databases from one server to another
mysqldbexport     export metadata and data from databases
mysqldbimport     import metadata and data from files
mysqldiff         compare object definitions among objects where the
                  difference is how db1.obj1 differs from db2.obj2
mysqldiskusage    show disk usage for databases
mysqlfailover     automatic replication health monitoring and failover
mysqlfrm          show CREATE TABLE from .frm files
mysqlindexcheck   check for duplicate or redundant indexes
mysqlmetagrep     search metadata
mysqlprocgrep     search process information
mysqlreplicate    establish replication with a master
mysqlrpladmin     administration utility for MySQL replication
mysqlrplcheck     check replication
mysqlrplshow      show slaves attached to a master
mysqlserverclone  start another instance of a running server
mysqlserverinfo   show server information
mysqluserclone    clone a MySQL user account to one or more new users

In PANDAS, how to get the index of a known value?

Using the .loc[] accessor:

In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4

Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.

In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4

phantomjs not waiting for "full" page load

In my program, I use some logic to judge if it was onload: watching it's network request, if there was no new request on past 200ms, I treat it onload.

Use this, after onLoadFinish().

function onLoadComplete(page, callback){
    var waiting = [];  // request id
    var interval = 200;  //ms time waiting new request
    var timer = setTimeout( timeout, interval);
    var max_retry = 3;  //
    var counter_retry = 0;

    function timeout(){
        if(waiting.length && counter_retry < max_retry){
            timer = setTimeout( timeout, interval);
                callback(null, page);

    //for debug, log time cost
    var tlogger = {};

    bindEvent(page, 'request', function(req){

    bindEvent(page, 'receive', function (res) {
        var cT = res.contentType;
            console.log('[contentType] ', cT, ' [url] ', res.url);
        if(!cT) return remove(;
        if(cT.indexOf('application') * cT.indexOf('text') != 0) return remove(;

        if (res.stage === 'start') {
            console.log('!!received start: ',;
            //console.log( JSON.stringify(res) );
            tlogger[] = new Date();
        }else if (res.stage === 'end') {
            console.log('!!received end: ',, (new Date() - tlogger[]) );
            //console.log( JSON.stringify(res) );

            timer = setTimeout(timeout, interval);


    bindEvent(page, 'error', function(err){
        if(waiting.length === 0){
            counter_retry = 0;

    function remove(id){
        var i = waiting.indexOf( id );
        if(i < 0){

    function bindEvent(page, evt, cb){
            case 'request':
                page.onResourceRequested = cb;
            case 'receive':
                page.onResourceReceived = cb;
            case 'error':
                page.onResourceError = cb;
            case 'timeout':
                page.onResourceTimeout = cb;

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'


How to set top position using jquery

Just for reference, if you are using:


To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

How can I pass an Integer class correctly by reference?

1 ) Only the copy of reference is sent as a value to the formal parameter. When the formal parameter variable is assigned other value ,the formal parameter's reference changes but the actual parameter's reference remain the same incase of this integer object.

public class UnderstandingObjects {

public static void main(String[] args) {

    Integer actualParam = new Integer(10);


    System.out.println("Output " + actualParam); // o/p =10

    IntObj obj = new IntObj();



    System.out.println(obj.a); // o/p =200


private static void changeValue(Integer formalParam) {

    formalParam = 100;

    // Only the copy of reference is set to the formal parameter
    // this is something like => Integer formalParam =new Integer(100);
    // Here we are changing the reference of formalParam itself not just the
    // reference value


private static void changeValue(IntObj obj) {

     * obj = new IntObj(); obj.setVal(200);
    // Here we are not changing the reference of obj. we are just changing the
    // reference obj's value

    // we are not doing obj = new IntObj() ; obj.setValue(200); which has happend
    // with the Integer



class IntObj { Integer a;

public void setVal(int a) {
    this.a = a;


How do I disable log messages from the Requests library?

Let me copy/paste the documentation section which it I wrote about week or two ago, after having a problem similar to yours:

import requests
import logging

# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
import httplib
httplib.HTTPConnection.debuglevel = 1

logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.propagate = True


How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();

"Input string was not in a correct format."

whenever i try to compile the code it says "{"Input string was not in a correct format."}"

This error won't come on compiling.

Now the error comese because you are trying to parse an invalid string to integer. To do it in a safe manner, you should do it like this

int questionID;
if(int.TryParse(vTwoOrMoreOptions.SelectedItems[0].Text.ToString(),out questionID))
//success code
 //failure code

How to convert a String into an ArrayList?

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
    return charList;

But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
    return stringList;

Spring @PropertySource using YAML

it's because you have not configure snakeyml. spring boot come with @EnableAutoConfiguration feature. there is snakeyml config too when u call this annotation..

this is my way:

public class AppContextTest {

here is my test:

        classes = {

public class JaxbTest {
//tests are ommited

Scroll Element into View with Selenium

I have used this way for scrolling the element and click:

List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(@src,'image/plus_btn.jpg')]"));

for (WebElement clickimg : image)
  ((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);;

How do I create a crontab through a script

As a correction to those suggesting crontab -l | crontab -: This does not work on every system. For example, I had to add a job to the root crontab on dozens of servers running an old version SUSE (don't ask why). Old SUSEs prepend comment lines to the output of crontab -l, making crontab -l | crontab - non-idempotent (Debian recognizes this problem in the crontab manpage and patched its version of Vixie Cron to change the default behaviour of crontab -l).

To edit crontabs programmatically on systems where crontab -l adds comments, you can try the following:

EDITOR=cat crontab -e > old_crontab; cat old_crontab new_job | crontab -

EDITOR=cat tells crontab to use cat as an editor (not the usual default vi), which doesn't change the file, but instead copies it to stdout. This might still fail if crontab - expects input in a format different from what crontab -e outputs. Do not try to replace the final crontab - with crontab -e - it will not work.

How to change context root of a dynamic web project in Eclipse?

If using eclipse to deploy your application . We can use this maven plugin


now go to your project root folder and open cmd prompt at that location type this command :

mvn eclipse:eclipse -Dwtpversion=2.0

You may need to restart eclipse , or in server view delete server and create agian to see affect. I wonder this exercise make sense in real life but works.

Device not detected in Eclipse when connected with USB cable

Best approach is install PDA net(software) on both system as well as in android device. This software automatically installs global driver for all phones, provides easy connectivity to android device.

Follow these links to download

For system

For android device

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

For future reference:

 yyyy => 4 digit year
 MM   => 2 digit month (you must type MM in ALL CAPS)
 dd   => 2 digit "day of the month"

 HH   => 2-digit "hour in day" (0 to 23)
 mm   => 2-digit minute (you must type mm in lowercase)
 ss   => 2-digit seconds
 SSS  => milliseconds

So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"

But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"

The so-called examples at show only output. They do not tell you what formats to use!

Add button to navigationbar programmatically

In ViewDidLoad method of ViewController.m

UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];

[self.navigationItem setLeftBarButtonItem:cancel];

"(back)" selector is a method to dissmiss the current ViewController

Invalid default value for 'dateAdded'

mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP

What is the $$hashKey added to my JSON.stringify result

Angular adds this to keep track of your changes, so it knows when it needs to update the DOM.

If you use angular.toJson(obj) instead of JSON.stringify(obj) then Angular will strip out these internal-use values for you.

Also, if you change your repeat expression to use the track by {uniqueProperty} suffix, Angular won't have to add $$hashKey at all. For example

    <li ng-repeat="link in navLinks track by link.href">
        <a ng-href="link.href">{{link.title}}</a>

Just always remember you need the "link." part of the expression - I always tend to forget that. Just track by href will surely not work.

MySQL Event Scheduler on a specific time everyday

Try this

STARTS '2012-04-17 13:00:00' -- should be in the future
-- your statements

Generating a PNG with matplotlib when DISPLAY is undefined

I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.

import matplotlib

Or one would get error

*/usr/lib/pymodules/python2.7/matplotlib/ UserWarning:  This call to   matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*

This will resolve all Display issue

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

How to get coordinates of an svg element?

I use the consolidate function, like so:


The .e and .f values correspond to the x and y coordinates

Send JSON data from Javascript to PHP?

using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( ) to parse it in php. And then you can use it as an array.

Use jQuery to change value of a label

val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

How do I get the last character of a string using an Excel function?

Just another way to do this:

=MID(A1, LEN(A1), 1)

Angular2, what is the correct way to disable an anchor element?

Just came across this question, and wanted to suggest an alternate approach.

In the markup the OP provided, there is a click event binding. This makes me think that the elements are being used as "buttons". If that is the case, they could be marked up as <button> elements and styled like links, if that is the look you desire. (For example, Bootstrap has a built-in "link" button style,

This has several direct and indirect benefits. It allows you to bind to the disabled property, which when set will disable mouse and keyboard events automatically. It lets you style the disabled state based on the disabled attribute, so you don't have to also manipulate the element's class. It is also better for accessibility.

For a good write-up about when to use buttons and when to use links, see Links are not buttons. Neither are DIVs and SPANs

Random / noise functions for GLSL

It occurs to me that you could use a simple integer hash function and insert the result into a float's mantissa. IIRC the GLSL spec guarantees 32-bit unsigned integers and IEEE binary32 float representation so it should be perfectly portable.

I gave this a try just now. The results are very good: it looks exactly like static with every input I tried, no visible patterns at all. In contrast the popular sin/fract snippet has fairly pronounced diagonal lines on my GPU given the same inputs.

One disadvantage is that it requires GLSL v3.30. And although it seems fast enough, I haven't empirically quantified its performance. AMD's Shader Analyzer claims 13.33 pixels per clock for the vec2 version on a HD5870. Contrast with 16 pixels per clock for the sin/fract snippet. So it is certainly a little slower.

Here's my implementation. I left it in various permutations of the idea to make it easier to derive your own functions from.

    by Spatial
    05 July 2013

#version 330 core

uniform float time;
out vec4 fragment;

// A single iteration of Bob Jenkins' One-At-A-Time hashing algorithm.
uint hash( uint x ) {
    x += ( x << 10u );
    x ^= ( x >>  6u );
    x += ( x <<  3u );
    x ^= ( x >> 11u );
    x += ( x << 15u );
    return x;

// Compound versions of the hashing algorithm I whipped together.
uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y)                         ); }
uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z)             ); }
uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }

// Construct a float with half-open range [0:1] using low 23 bits.
// All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
float floatConstruct( uint m ) {
    const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
    const uint ieeeOne      = 0x3F800000u; // 1.0 in IEEE binary32

    m &= ieeeMantissa;                     // Keep only mantissa bits (fractional part)
    m |= ieeeOne;                          // Add fractional part to 1.0

    float  f = uintBitsToFloat( m );       // Range [1:2]
    return f - 1.0;                        // Range [0:1]

// Pseudo-random value in half-open range [0:1].
float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
float random( vec2  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec3  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec4  v ) { return floatConstruct(hash(floatBitsToUint(v))); }

void main()
    vec3  inputs = vec3( gl_FragCoord.xy, time ); // Spatial and temporal inputs
    float rand   = random( inputs );              // Random per-pixel value
    vec3  luma   = vec3( rand );                  // Expand to RGB

    fragment = vec4( luma, 1.0 );


Output of random(vec3) in static.frag

I inspected the screenshot in an image editing program. There are 256 colours and the average value is 127, meaning the distribution is uniform and covers the expected range.

Toggle input disabled attribute using jQuery

Another simple option that updates on a click of the checkbox.


<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>


$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   

In action: link

How to sort an object array by date property?

Simplest Answer

  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date( - new Date(;

More Generic Answer

  if (sort_o1_before_o2)    return -1;
  else if(sort_o1_after_o2) return  1;
  else                      return  0;

Or more tersely:

  return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;

Generic, Powerful Answer

Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :

  if (typeof Object.defineProperty === 'function'){
    try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
  if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

  function sb(f){
    for (var i=this.length;i;){
      var o = this[--i];
      this[i] = [].concat(,o,i),o);
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
      return 0;
    for (var i=this.length;i;){
    return this;

Use it like so:

array.sortBy(function(o){ return });

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( ) });

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [, -o.score, ] };

See for more details.

FIX CSS <!--[if lt IE 8]> in IE

Also, the comment tag


is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as

<!--[if lte IE 8]><![endif]-->

In which lte means "less than or equal to".

See: Conditional Comments.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

in your Xcode:

  • Click on your active scheme name right next to the Stop button
  • Click on Edit Scheme....
  • in Run (Debug) select the Arguments tab
  • in Environment Variables click +
  • add variable: OS_ACTIVITY_MODE = disable


How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

In what cases do I use malloc and/or new?

From the C++ FQA Lite:

[16.4] Why should I use new instead of trustworthy old malloc()?

FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class.

FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe").

Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something.

Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.

Sorry, I just couldn't resist. :)

Hashing with SHA1 Algorithm in C#

This is what I went with. For those of you who want to optimize, check out

    public static string Hash(string stringToHash)
        using (var sha1 = new SHA1Managed())
            return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));

Add space between <li> elements

Most answers here are not correct as they would add bottom space to the last <li> as well, so they are not adding space ONLY in between <li> !

The most accurate and efficient solution is the following: { 
   margin-bottom: 3px;  

Explanation: by using :not(:last-child) the style will be applie to all items ( but the last one.

How to change color of ListView items on focus and on click

Very old but I have just struggled with this, this is how I solved it in pure xml. In res/values/colors.xml I added three colours (the colour_...);


    <color name="black_overlay">#66000000</color>

    <color name="colour_highlight_grey">#ff666666</color>
    <color name="colour_dark_blue">#ff000066</color>
    <color name="colour_dark_green">#ff006600</color>


In the res/drawable folder I created listview_colours.xml which contained;

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:drawable="@color/colour_highlight_grey" android:state_pressed="true"/>
    <item android:drawable="@color/colour_dark_blue" android:state_selected="true"/>
    <item android:drawable="@color/colour_dark_green" android:state_activated="true"/>
    <item android:drawable="@color/colour_dark_blue" android:state_focused="true"/>

In the main_activity.xml find the List View and add the drawable to listSelector;


Play with the state_... items in the listview_colours.xml to get the effect you want.

There is also a method where you can set the style of the List View but I never managed to get it to work

How to extract custom header value in Web API message handler?

This may sound obvious, but make sure the Controller where you are reading the headers in, is the first Controller where the request goes through.

I had two WebAPI projects communicating with each other. The first one was a proxy, the second contained the logic. Silly me, I tried reading the custom headers in the second Controller, instead of the first one.

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces


If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;


// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');

Create dynamic variable name

No. That is not possible. You should use an array instead:

name[i] = i;

In this case, your name+i is name[i].

What is the Swift equivalent of respondsToSelector?

I just implement this myself in a project, see code below. As mentions by @Christopher Pickslay it is important to remember that functions are first class citizens and can therefore be treated like optional variables.

@objc protocol ContactDetailsDelegate: class {

    optional func deleteContact(contact: Contact) -> NSError?


weak var delegate:ContactDetailsDelegate!

if let deleteContact = delegate.deleteContact {

JavaScript to get rows count of a HTML table

Given a

<table id="tableId">
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>

and a

var table = document.getElementById("tableId");

there are two ways to count the rows:

var totalRowCount = table.rows.length; // 5
var tbodyRowCount = table.tBodies[0].rows.length; // 3

The table.rows.length returns the amount of ALL <tr> elements within the table. So for the above table it will return 5 while most people would really expect 3. The table.tBodies returns an array of all <tbody> elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3.

Difference between web reference and service reference?

Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)

C++ program converts fahrenheit to celsius

Best way would be

#include <iostream>                        
using namespace std;                       

int main() {                               
    float celsius;                         
    float fahrenheit;

    cout << "Enter Celsius temperature: "; 
    cin >> celsius;
    fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
    cout << "Fahrenheit = " << fahrenheit << endl;

    return 0;                             


Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

how to make div click-able?

I suggest to use jQuery:

  .css('cursor', 'pointer')
     alert('Click event is fired');
      $(this).css('background', '#ff00ff');
      $(this).css('background', '');

What is the right way to populate a DropDownList from a database?

public void getClientNameDropDowndata()
    getConnection = Connection.SetConnection(); // to connect with data base Configure manager
    string ClientName = "Select  ClientName from Client ";
    SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
    ClientNameCommand.CommandType = CommandType.Text;
    SqlDataReader ClientNameData;
    ClientNameData = ClientNameCommand.ExecuteReader();
    if (ClientNameData.HasRows)
        DropDownList_ClientName.DataSource = ClientNameData;
        DropDownList_ClientName.DataValueField = "ClientName";
        MessageBox.Show("No is found");
        CloseConnection = new Connection();
        CloseConnection.closeConnection(); // close the connection 

Kill some processes by .exe file name

You can Kill a specific instance of MS Word.

foreach (var process in Process.GetProcessesByName("WINWORD"))
    // Temp is a document which you need to kill.
    if (process.MainWindowTitle.Contains("Temp")) 

Session state can only be used when enableSessionState is set to true either in a configuration

  1. Could be your skype intercepting your requests at 80 port, in Skype options uncheck
  2. Or Your IE has connection checked for Proxy when there is no proxy
  3. Or your fiddler could intercept and act as proxy, uncheck it!

Solves the above problem, It solved mine!


How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];


Should I use <i> tag for icons instead of <span>?

I also found this to be useful when i wanted to place an icon with absolute positioning inside a link <a> tag.

I thought about the <img> tag first, but default styling of those tags inside links typically have border styling and/or shadow effects. Plus, it feels wrong to use an <img> tag without defining an "src" attribute whereas i'm using a background-image style sheet declaration so that the image doesn't ghost and drag.

At this point you're thinking of tags like <span> or <i> - in which case <i> makes so much sense as this type of icon.

All in all i think its benefit besides being intuitive is that it requires minimal style sheet adjustments to make this tag work as an icon.

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        for (int i = 0; i < treeView1.Nodes.Count; i++)
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)

Is there a git-merge --dry-run option?

My solution is to merge backwards.

Instead of merging your branch into the remote "target" branch, merge that branch into yours.

git checkout my-branch
git merge origin/target-branch

You will see if there are any conflicts and can plan on how to solve them.

After that you can either abort the merge via git merge --abort, or (if there weren't any conflicts and merge has happened) roll back to previous commit via git reset --hard HEAD~1

How to upload and parse a CSV file in php

This can be done in a much simpler manner now.

$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));

This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.

Android disable screen timeout while app is running

Put this at onStart

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep");

And this at you manifest

    <uses-permission android:name="android.permission.WAKE_LOCK" />

Don't forget to


at onStop

Checking if a variable is initialized

If you mean how to check whether member variables have been initialized, you can do this by assigning them sentinel values in the constructor. Choose sentinel values as values that will never occur in normal usage of that variable. If a variables entire range is considered valid, you can create a boolean to indicate whether it has been initialized.

#include <limits>

class MyClass
    void SomeMethod();

    char mCharacter;
    bool isCharacterInitialized;
    double mDecimal;

    : isCharacterInitialized(false)
    , mDecimal( std::numeric_limits<double>::quiet_NaN() )


void MyClass::SomeMethod()
    if ( isCharacterInitialized == false )
        // do something with mCharacter.

    if ( mDecimal != mDecimal ) // if true, mDecimal == NaN
        // define mDecimal.

Express.js: how to get remote client address

I wrote a package for that purpose. You can use it as express middleware. My package is published here:

You can install the module using

npm i express-ip


const express = require('express');
const app = express();
const expressip = require('express-ip');

app.get('/', function (req, res) {

How do I send an HTML email?

You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("", "");
  props.put("mail.smtp.port", "587");

How do I truncate a .NET string?

A similar variant with C# 6's Null propagation operator

public static string Truncate(this string value, int maxLength)
    return value?.Length <= maxLength ? value : value?.Substring(0, maxLength);

Please note, we are essentially checking if value is null twice here.

JavaScript - populate drop down list with array

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;

Live example

Git push rejected after feature branch rebase

The problem is that git push assumes that remote branch can be fast-forwarded to your local branch, that is that all the difference between local and remote branches is in local having some new commits at the end like that:

Z--X--R         <- origin/some-branch (can be fast-forwarded to Y commit)
        T--Y    <- some-branch

When you perform git rebase commits D and E are applied to new base and new commits are created. That means after rebase you have something like that:

A--B--C------F--G--D'--E'   <- feature-branch
        D--E                <- origin/feature-branch

In that situation remote branch can't be fast-forwarded to local. Though, theoretically local branch can be merged into remote (obviously you don't need it in that case), but as git push performs only fast-forward merges it throws and error.

And what --force option does is just ignoring state of remote branch and setting it to the commit you're pushing into it. So git push --force origin feature-branch simply overrides origin/feature-branch with local feature-branch.

In my opinion, rebasing feature branches on master and force-pushing them back to remote repository is OK as long as you're the only one who works on that branch.

log4j logging hierarchy order


Check whether number is even or odd

If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:

public void evenOrOddNumber(int number) {
  if (number % 2 == 0) {
    System.out.println("Number is Even");
   } else {
    System.out.println("Number is odd");

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.

In Help, About, the 64-bit version of IE will say 64-bit Edition (just after the full version string).

The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.

In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32.

Commenting out a set of lines in a shell script

What if you just wrap your code into function?

So this:

cd ~/documents
mkdir test
echo "useless script" > about.txt

Becomes this:

CommentedOutBlock() {
  cd ~/documents
  mkdir test
  echo "useless script" > about.txt

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

phpexcel to download

$excel = new PHPExcel();
header('Content-Type: application/');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

// This line will force the file to download

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 


Override hosts variable of Ansible playbook from the command line

I'm using another approach that doesn't need any inventory and works with this simple command:

ansible-playbook site.yml -e working_host=myhost

To perform that, you need a playbook with two plays:

  • first play runs on localhost and add a host (from given variable) in a known group in inmemory inventory
  • second play runs on this known group

A working example (copy it and runs it with previous command):

- hosts: localhost
  connection: local
  - add_host:
      name: "{{ working_host }}"
      groups: working_group
    changed_when: false

- hosts: working_group
  gather_facts: false
  - debug:
      msg: "I'm on {{ ansible_host }}"

I'm using ansible 2.4.3 and 2.3.3

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

Using custom std::set comparator

You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

struct lex_compare {
    bool operator() (const int64_t& lhs, const int64_t& rhs) const {
        stringstream s1, s2;
        s1 << lhs;
        s2 << rhs;
        return s1.str() < s2.str();

You then use the class name as the type parameter

set<int64_t, lex_compare> s;

If you want to avoid the functor boilerplate code you can also use a function pointer (assuming lex_compare is a function).

set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);

How to test Spring Data repositories?

With JUnit5 and @DataJpaTest test will look like (kotlin code):

@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {

    lateinit var entityManager: TestEntityManager

    lateinit var myEntityRepository: MyEntityRepository

    fun shouldSaveEntity() {
        // when
        val savedEntity =, "test")

        // then 

You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

How SID is different from Service name in Oracle tnsnames.ora

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

Java Equivalent of C# async/await?

AsynHelper Java library includes a set of utility classes/methods for such asynchronous calls (and wait).

If it is desired to run a set of method calls or code blocks asynchronously, the It includes an useful helper method AsyncTask.submitTasks as in below snippet.

    () -> getMethodParam1(arg1, arg2),
    () -> getMethodParam2(arg2, arg3)
    () -> getMethodParam3(arg3, arg4),
    () -> {
             //Some other code to run asynchronously

If it is desired to wait till all asynchronous codes are completed running, the AsyncTask.submitTasksAndWait varient can be used.

Also if it is desired to obtain a return value from each of the asynchronous method call or code block, the AsyncSupplier.submitSuppliers can be used so that the result can be then obtained by from the result suppliers array returned by the method. Below is the sample snippet:

Supplier<Object>[] resultSuppliers = 
     () -> getMethodParam1(arg1, arg2),
     () -> getMethodParam2(arg3, arg4),
     () -> getMethodParam3(arg5, arg6)

Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();


If the return type of each method differ, use the below kind of snippet.

Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));

myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());

The result of the asynchronous method calls/code blocks can also be obtained at a different point of code in the same thread or a different thread as in the below snippet.

AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");

//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");


Open Sublime Text from Terminal in macOS

You can create a new alias in Terminal:

nano ~/.bash_profile

Copy this line and paste it into the editor:

alias subl='open -a "Sublime Text"'

Hit control + x, then y, then enter to save and close it.

Close all Terminal windows and open it up again.

That's it, you can now use subl filename or subl .

MySQL date formats - difficulty Inserting a date

When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:

$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";

How to stop app that node.js express 'npm start'

kill $(lsof -t -i :PORT_TO_KILL)

simplified version. Simple copy paste with the port to kill ex.5000

What is the difference between 'E', 'T', and '?' for Java generics?

compiler will make a capture for each wildcard (e.g., question mark in List) when it makes up a function like:

foo(List<?> list) {
    list.put(list.get()) // ERROR: capture and Object are not identical type.

However a generic type like V would be ok and making it a generic method:

<V>void foo(List<V> list) {

Setting a system environment variable from a Windows batch file?

Simple example for how to set JAVA_HOME with setx.exe in command line:

setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "-m". Here is an example:

setx -m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

Note: you have to execute this command as Administrator.

Note: Make sure to run the command setx from an command-line Admin window

How to convert file to base64 in JavaScript?

Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
      if ((encoded.length % 4) > 0) {
        encoded += '='.repeat(4 - (encoded.length % 4));
    reader.onerror = error => reject(error);

Linq style "For Each"

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
    list.Add(x + 1);

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
   foreach (var x in @this)

NGINX to reverse proxy websockets AND enable SSL (wss://)?

Just to note that nginx has now support for Websockets on the release 1.3.13. Example of use:

location /websocket/ {

    proxy_pass ?http://backend_host;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;


You can also check the nginx changelog and the WebSocket proxying documentation.

pandas convert some columns into rows

Use set_index with stack for MultiIndex Series, then for DataFrame add reset_index with rename:

df1 = (df.set_index(["location", "name"])
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25

Launch an app on OS X with command line

In case your app needs to work on files (what you would normally expect to pass as: ./myApp *.jpg), you would do it like this:

open *.jpg -a myApp

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas:

The monkey patch detailed on this issue has resolved the problem for me:


# Solving memory leak problem in pandas
import pandas as pd
from ctypes import cdll, CDLL
    libc = CDLL("")
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How to select the first element in the dropdown using jquery?

Your selector is wrong, you were probably looking for

$('select option:nth-child(1)')

This will work also:

$('select option:first-child')

How to calculate the inverse of the normal cumulative distribution function in python?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the inverse cumulative distribution function (inv_cdf - inverse of the cdf), also known as the quantile function or the percent-point function for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

# 1.6448536269514715

How can I check if a string represents an int, without using try/except?

If you want to accept lower-ascii digits only, here are tests to do so:

Python 3.7+: (u.isdecimal() and u.isascii())

Python <= 3.6: (u.isdecimal() and u == str(int(u)))

Other answers suggest using .isdigit() or .isdecimal() but these both include some upper-unicode characters such as '?' (u'\u0662'):

u = u'\u0662'     # '?'
u.isdigit()       # True
u.isdecimal()     # True
u.isascii()       # False (Python 3.7+ only)
u == str(int(u))  # False

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then, and are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

What is the difference between dynamic programming and greedy approach?

In simple words we can say that in Dynamic Programming (having problem sending message on network) one can first examine the path which takes the shortest time and then start journey,

On the other hand Greedy algorithm take the optimal decision on the spot without thinking for the next step and on the next step change its decision again and so on...

Notes: Dynamic programming is reliable while Greedy Algorithms is not reliable always.

How to return data from promise

You have to return a promise instead of a variable. So in your function just return:

return relationsManagerResource.GetParentId(nodeId)

And later resolve the returned promise. Or you can make another deferred and resolve theParentId with it.

CSS disable hover effect

To disable the hover effect, I've got two suggestions:

  • if your hover effect is triggered by JavaScript, just use $.unbind('hover');
  • if your hover style is triggered by class, then just use $.removeClass('hoverCssClass');

Using CSS !important to override CSS will make your CSS very unclean thus that method is not recommended. You can always duplicate a CSS style with different class name to keep the same styling.

C# Set collection?

If you're using .NET 3.5, you can use HashSet<T>. It's true that .NET doesn't cater for sets as well as Java does though.

The Wintellect PowerCollections may help too.

Running Facebook application on localhost

You can also edit 'hosts' file and create local variation of your domain.


If your real facebook application address is "" you can create "" (accessible only from your pc) domain in your "hosts" file pointing to "localhost" and run your local website under this domain. You can trick Facebook this way.

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

ASP.NET MVC - Getting QueryString values

I think what you are looking for is


and you can access it on views by adding @

now look at my example,,, I generated a Url with QueryString

 var listURL = '@Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';

the listURL value is /Sector/List?name=value'

and when queryString is empty

listURL value is /Sector/List

Android Studio Gradle Configuration with name 'default' not found

compile fileTree(dir: '//you libraries location//', include: ['android-ColorPickerPreference'])

Use above line in your app's gradle file instead of

compile project(':android-ColorPickerPreference')

Hope it helps

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:


UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                    } else {


                input.find("tr").each(function () {

    $(document).ready(function () {


<table id="Table1" class="full">

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

How to get the data-id attribute?

If you are not concerned about old IE browsers, you can also use HTML5 dataset API


<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>


var myDiv = document.querySelector('#my-div'); // "some info here"
myDiv.dataset.otherInfo // "more info here"


Full browser support list:

Can HTTP POST be limitless?

Quite amazing how all answers talk about IIS, as if that were the only web server that mattered. Even back in 2010 when the question was asked, Apache had between 60% and 70% of the market share. Anyway,

  • The HTTP protocol does not specify a limit.
  • The POST method allows sending far more data than the GET method, which is limited by the URL length - about 2KB.
  • The maximum POST request body size is configured on the HTTP server and typically ranges from
    1MB to 2GB
  • The HTTP client (browser or other user agent) can have its own limitations. Therefore, the maximum POST body request size is min(serverMaximumSize, clientMaximumSize).

Here are the POST body sizes for some of the more popular HTTP servers:

Retrieve the position (X,Y) of an HTML element relative to the browser window

After much research and testing this seems to work

function getPosition(e) {
    var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
    var x = 0, y = 0;
    while (e) {
        x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
        y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
        e = e.offsetParent;
    return { x: x + window.scrollX, y: y + window.scrollY };


libpng warning: iCCP: known incorrect sRGB profile


The incorrect profile could be fixed by:

  1. Opening the image with the incorrect profile using QPixmap::load
  2. Saving the image back to the disk (already with the correct profile) using QPixmap::save

Note: This solution uses the Qt Library.


Here is a minimal example I have written in C++ in order to demonstrate how to implement the proposed solution:

QPixmap pixmap;

QFile file("goodProfileImage.png");;, "PNG");

The complete source code of a GUI application based on this example is available on GitHub.

UPDATE FROM 05.12.2019: The answer was and is still valid, however there was a bug in the GUI application I have shared on GitHub, causing the output image to be empty. I have just fixed it and apologise for the inconvenience!

CSS I want a div to be on top of everything

I gonna assumed you making a popup with code from WW3 school, correct? check it css. the .modal one, there're already word z-index there. just change from 1 to 100.

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

In such cases a common trick is (was?) to go backwards:

for(int i = l.size() - 1; i >= 0; i --) {
  if (l.get(i) == 5) {

That said, I'm more than happy that you have better ways in Java 8, e.g. removeIf or filter on streams.

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        {{ section.text }}


get_data(event) {

Error:(23, 17) Failed to resolve: junit:junit:4.12

The error is caused by missing jar files. My simple solution is just by copying all the files that does not resolve to the C:\Program Files\Android\Android Studio\gradle\m2repository... (your file path may be different). I got around 6 dependencies that cannot be resolved, junit is one of them and the others are com and org and javax. Since I am behind a firewall, even if I added the code for the repository, the Android Studio doesn't seem to access it. I went to the maven repository and downloaded all the files that will not resolve. Problem solved and the Gradle sync without error. But I am a certified newbie with only 1 day experience so I do not not if this is the proper way to do it.

Example error: Cannot resolve com:squareup:javawriter:2.1.1

Step 1: I created a path C:\Program Files\Android\Android Studio\gradle\m2repository\com\squareup\javawriter\2.1.1\

Step 2: I downloaded all the jar files from the maven repository:

Step 3: I manually downloaded all the .jar files from this directory

Step 4: I copied them to C:\Program Files\Android\Android Studio\gradle\m2repository\com\squareup\javawriter\2.1.1\

I repeated this to all the files that did not resolve including the junit.

For junit, here is the directory I created: C:\Program Files\Android\Android Studio\gradle\m2repository\junit\junit\4.12 and then I copied the junit-4.12.jar inside this directory and the junit error disappeared.

Bash command to sum a column of numbers

You can use bc (calculator). Assuming your file with #s is called "n":

$ cat n
$ (cat n | tr "\012" "+" ; echo "0") | bc 

The tr changes all newlines to "+"; then we append 0 after the last plus, then we pipe the expression (1+2+3+0) to the calculator

Or, if you are OK with using awk or perl, here's a Perl one-liner:

$perl -nle '$sum += $_ } END { print $sum' n

How to get element value in jQuery

$("#list li").click(function() {
        var selected = $(this).html();

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.

Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)

Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

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

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

C# : changing listbox row color?

I find the solution for listbox items' background to yellow. I tried the following solution to achieve the output.

 for (int i = 0; i < lstEquipmentItem.Items.Count; i++)
                    if ((bool)ds.Tables[0].Rows[i]["Valid_Equipment"] == false)
                        lblTKMWarning.Text = "Invalid Equipment & Serial Numbers are highlited.";
                        lblTKMWarning.ForeColor = System.Drawing.Color.Red;
                        lstEquipmentItem.Items[i].Attributes.Add("style", "background-color:Yellow");


Can't connect to localhost on SQL Server Express 2012 / 2016

Goto Start -> Programs -> Microsoft SQL ServerYYYY -> Configuration Tools -> SQL Server YYYY Configuration Manager or run "SQLServerManager12.msc".

Make sure that TCP/IP is enabled under Client Protocols.

Then go into "SQL Server Network Configuration" and double click TCP/IP. Click the "IP Addresses" tab and scroll to the bottom. Under "IP All" remove TCP Dynamic Ports if it is present and set TCP Port to 1433. Click OK and then go back to "SQL Server Services" and restart SQL Server instance. Now you can connect via localhost, at least I could.

enter image description here

Note that this error can of course occur when connecting from other applications as well. Example for a normal C# web application Web.config connection string:

    <add name="DefaultConnection" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

What is PECS (Producer Extends Consumer Super)?

Covariance: accept subtypes
Contravariance: accept supertypes

Covariant types are read-only, while contravariant types are write-only.

How do you get the index of the current iteration of a foreach loop?

You can write your loop like this:

var s = "ABCDEFG";
foreach (var item in s.GetEnumeratorWithIndex())
    System.Console.WriteLine("Character: {0}, Position: {1}", item.Value, item.Index);

After adding the following struct and extension method.

The struct and extension method encapsulate Enumerable.Select functionality.

public struct ValueWithIndex<T>
    public readonly T Value;
    public readonly int Index;

    public ValueWithIndex(T value, int index)
        this.Value = value;
        this.Index = index;

    public static ValueWithIndex<T> Create(T value, int index)
        return new ValueWithIndex<T>(value, index);

public static class ExtensionMethods
    public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable)
        return enumerable.Select(ValueWithIndex<T>.Create);

Apache won't follow symlinks (403 Forbidden)

For anyone having trouble after upgrading to 14.04 as root changed before upgrade = /var/www after upgrade = /var/www/html

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame =
    if cv.waitKey(20) & 0xFF==ord('d'):


0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

Android - Spacing between CheckBox and text

If you have custom image selector for checkbox or radiobutton you must set same button and background property such as this:

                android:background="@drawable/selector_checkbox_filter" />

You can control size of checkbox or radio button padding with background property.