Programs & Examples On #Valign

Valign is an HTML attribute used to designate a vertical alignment of an entity.

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>


// authentication servlet class

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {


        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
            } catch (ClassNotFoundException e) {

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while ( {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");

            } catch (SQLException e) {



Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]

<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.


Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     <td style="height:40px; width:10px; margin:0;">        
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\ in line no 124 you are trying to access a null object which results in null pointer exception.

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

Uncaught ReferenceError: $ is not defined

If you are doing this in .Net and have the script file referenced properly and you jQuery looks fine, make sure that your users have access to the script file. The project I was working on (a coworker) had their web.config denying access to anonymous users. The page I was working on was accessible to anonymous users therefore they didn't have access to the script file. Dropped the following into the web.config and all was right in the world:

  <location path="Scripts">
        <allow users="*"/>

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

jQuery append and remove dynamic table row

In addition to the other answers, I'd like to improve the removal, to something more generic:


This would be much better than using $(this).parent().parent().remove();, because it doesn't depend on the depth of the element. So, the structure of the row becomes much more flexible.

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    else {
        // DO NOTHING

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World

Table Height 100% inside Div element

Not possible without assigning height value to div.

Add this

body, html{height:100%}
table{background:green; width:450px}    ?


Read a HTML file into a string variable in memory

What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument(); followed by doc.Load(filename). Then the XML document can be parsed in memory.

Read here for more information on XmlDocument:

How to change background color of cell in table using java script

Try this:

function btnClick() {
    var x = document.getElementById("mytable").getElementsByTagName("td");
    x[0].innerHTML = "i want to change my cell color";
    x[0].style.backgroundColor = "yellow";            

Set from JS, backgroundColor is the equivalent of background-color in your style-sheet.

Note also that the .cells collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName().


You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

td widths, not working?

I use

<td nowrap="nowrap">

to prevent wrap Reference:

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().

Example of Unpredictable Error:

 <?php //a white-space before <?php also send for output and arise error

//your page content

One more example:

includes 'functions.php';
?> <!-- This new line will also arise error -->

//your page content

Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

JavaScript get element by name

All Answers here seem to be outdated. Please use this now:


javascript - pass selected value from popup window to parent window input box

(parent window)

<script language="javascript"> 
function openWindow() {"target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 

(child window)

<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 

Positioning <div> element at center of screen

Another easy flexible approach to display block at center: using native text alignment with line-height and text-align.


.parent {
    line-height: 100vh;        
    text-align: center;

.child {
    display: inline-block;
    vertical-align: middle;
    line-height: 100%;

And html sample:

<div class="parent">
  <div class="child">My center block</div>

We make div.parent fullscreen, and his single child div.child align as text with display: inline-block.


  • flexebility, no absolute values
  • support resize
  • works fine on mobile

Simple example on JSFiddle:

jquery - How to determine if a div changes its height or any css attribute?

Another simple example.

For this sample we can use 100x100 DIV-box:

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...

And small jQuery trick:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");


  1. We created DIV block element for resizing operatios
  2. Add simple JavaScript code with:
    • jQuery bind
    • jQuery resizer with trigger action "resize" - trigger is most important thing in my example
  3. After resize you can check the browser alert information

That's all. ;-)

How do I remove link underlining in my HTML email?

While viewing the html email try inspecting the element on that link and see what is overwriting it. Use that class and define it that style again in your head style and define the text-decoration: none !important;

In my case these are the classes that are overwriting my inline style so declared this on the head of my html email and defined the style that I want implemented.

It worked for me, hope it will work on your one too.

.ii a[href]{
text-decoration: none !important;

#yiv8915438996 a:link, #yiv8915438996 span.yiv8915438996MsoHyperlink{
text-decoration: none !important;

#yiv8915438996 a:visited, #yiv8915438996 span.yiv8915438996MsoHyperlinkFollowed{
text-decoration: none !important;

How to find tags with only certain attributes - BeautifulSoup

if you want to only search with attribute name with any value

from bs4 import BeautifulSoup
import re

soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})

as per Steve Lorimer better to pass True instead of regex

results = soup.findAll("td", {"valign" : True})

Uncaught ReferenceError: jQuery is not defined

In my case, the error occurred because I was using the wrong version of jquery.

<script src=""></script>

I changed it to:

<script src=""></script>

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

Not sure if this is what you're referring to, but this is the list of HTML entities you can use:

List of XML and HTML character entity references

Using the content within the 'Name' column you can just wrap these in an & and ;

E.g. &nbsp;, &emsp;, etc.

JQuery, select first row of table

Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

Wrong way:

var $row = $(this).closest('table').children('tr:first');

Correct way:

 var $row = $(this).closest('table').find('tr:first');

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

This should solve your problem:

td {
    /* <>
     * left, right, center, justify, inherit
    text-align: center;
    /* <>
     * baseline, sub, super, top, text-top, middle,
     * bottom, text-bottom, length, or a value in percentage
    vertical-align: top;

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if ( targ =;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;


onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;



<table id="main"><tr>


top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;

What are .tpl files? PHP, web design

That looks like Smarty to me. Smarty is a template parser written in PHP.

You can read up on how to use Smarty in the documentation.

If you can't get access to the CMS's source: To view the templates in your browser, just look at what variables Smarty is using and create a PHP file that populates the used variables with dummy data.

If I remember correctly, once Smarty is set up, you can use:

$smarty->assign('nameofvar', 'some data');

to set the variables.

Set colspan dynamically with jquery

I have adapted the script from Russ Cam (thank you, Russ Cam!) to my own needs: I needed to merge any columns that had the same value, not just empty cells.

This could be useful to someone else... Here is what I have come up with:

jQuery(document).ready(function() {

   jQuery('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;
    var strLookupText = '';

    jQuery('td', tr).each(function(index, value) {
      var td = jQuery(this);

      if ((td.text() == strLookupText) || (td.text() == "")) {
        td.prev().attr('colSpan', '' + parseInt(counter + 1,10) + '').css({textAlign : 'center'});
      else {
        counter = 0;

      // Sets the strLookupText variable to hold the current value. The next time in the loop the system will check the current value against the previous value.
      strLookupText = td.text();




HTML CSS How to stop a table cell from expanding

Simply set the max-width attribute to 280px like this:

<td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" max-width="280px" width="280px">

This will solve your problem.

Button inside of anchor link works in Firefox but not in Internet Explorer?

Since this is only an issue in IE, to resolve this, I'm first detecting if the browser is IE and if so, use a jquery click event. I put this code into a global file so it's fixed throughout the site.

if (navigator.appName === 'Microsoft Internet Explorer')
    $('a input.button').click(function()
        window.location = $(this).closest('a').attr('href');

This way we only have the overhead of assigning click events to linked input buttons for IE. note: The above code is inside a document ready function to make sure the page is completely loaded before assigning click events.

I also assigned class names to my input buttons to save some overhead when using IE so I can search for

$('a input.button')

instead of

$('a input[type=button]')


<a href="some_link"><input type="button" class="button" value="some value" /></a>

On top of all that, I'm also utilizing CSS to make the buttons look clickable when your mouse hovers over it:

input.button {cursor: pointer}

How to simulate a click by using x,y coordinates in JavaScript?

it doenst work for me but it prints the correct element to the console

this is the code:

function click(x, y)
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y

    var el = document.elementFromPoint(x, y);
    console.log(el); //print element to console
click(400, 400);

What are the benefits to marking a field as `readonly` in C#?

The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.

Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).

Format output string, right alignment

Here is another way how you can format using 'f-string' format:

    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.

How can I get an int from stdio in C?

The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.

printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);


> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234

How to execute a Python script from the Django shell?

if you have not a lot commands in your script use it: shell --command="import django; print(django.__version__)"

Django docs

How to override Bootstrap's Panel heading background color?

am assuming custom_class to be your class to override heading color of the panel. just add !important to it or add inline styles or a id and add styles as they will have more specificity over class added styles.

  • with !important

    .custom_class{ background-color: red !important; }

  • with !important

  • with ID :

    #custom_id{ background-color: red; }

-with inline styles :

<div id="custom_id" class="panel panel-default">
      <div class="panel-heading custom_class" style="background-color:red">

Network usage top/htop on Linux

Also iftop:

display bandwidth usage on an interface

iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))

Should work just right. I have used the comparison functions provided by Carbon.

Accessing elements of Python dictionary by index

As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:

sampleDict = {
              "key1": {"key10": "value10", "key11": "value11"},
              "key2": {"key20": "value20", "key21": "value21"}

So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values() list, you may use something like this:

for key, value in sampleDict.items():
    print value.keys()[0]

If you want to just access first key of the first item in sampleDict.values(), this may be useful:

print sampleDict.values()[0].keys()[0]

If you use the example you gave in the question, I mean:

sampleDict = {
              'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},

The output for the first code is:


And the output for the second code is:



Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys and values from list to dict_values. Type dict_values is not accepting indexing, but it is iterable. So you need to change above codes as below:

First One:

for key, value in sampleDict.items():

Second One:


Change color of bootstrap navbar on hover link?

Something like this has worked for me (with Bootstrap 3):

.navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus{
    font-family: proxima-nova;
    font-style: normal;
    font-weight: 100;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: black;

In my case I also wanted the link text to remain black before the hover so i added .navbar-nav > li > a

.navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus, .navbar-nav > li > a{
    font-family: proxima-nova;
    font-style: normal;
    font-weight: 100;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: black;

How to get a file directory path from file path?

$ export VAR=/home/me/mydir/file.c
$ export DIR=${VAR%/*}
$ echo "${DIR}"

$ echo "${VAR##*/}"

To avoid dependency with basename and dirname

Error: could not find function ... in R

If you are using parallelMap you'll need to export custom functions to the slave jobs, otherwise you get an error "could not find function ".

If you set a non-missing level on parallelStart the same argument should be passed to parallelExport, else you get the same error. So this should be strictly followed:

parallelStart(mode = "<your mode here>", N, level = "<task.level>")
parallelExport("<myfun>", level = "<task.level>")

Android EditText Max Length

If you want to see a counter label you can use app:counterEnabled and android:maxLength, like:


    android:maxLength="420" />


DO NOT set app:counterMaxLength on TextInputLayout because it will conflict with android:maxLength resulting into the issue of invisible chars after the text hits the size limit.

Convert Xml to DataTable

How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.

There is also a DataTable.ReadXml method.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''

because there are '\n' hide in the string. The url in fact become:


Templated check for the existence of a class member function?

Here are some usage snippets: *The guts for all this are farther down

Check for member x in a given class. Could be var, func, class, union, or enum:

bool has_x = has_member_x<class_to_check_for_x>::value;

Check for member function void x():

//Func signature MUST have T as template variable here... simpler this way :\
CREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);
bool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;

Check for member variable x:

bool has_var_x = has_member_var_x<class_to_check_for_x>::value;

Check for member class x:

bool has_class_x = has_member_class_x<class_to_check_for_x>::value;

Check for member union x:

bool has_union_x = has_member_union_x<class_to_check_for_x>::value;

Check for member enum x:

bool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;

Check for any member function x regardless of signature:

bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;


CREATE_MEMBER_CHECKS(x);  //Just stamps out the same macro calls as above.
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

Details and core:

    - Multiple inheritance forces ambiguity of member names.
    - SFINAE is used to make aliases to member names.
    - Expression SFINAE is used in just one generic has_member that can accept
      any alias we pass it.

//Variadic to force ambiguity of class members.  C++11 and up.
template <typename... Args> struct ambiguate : public Args... {};

//Non-variadic version of the line above.
//template <typename A, typename B> struct ambiguate : public A, public B {};

template<typename A, typename = void>
struct got_type : std::false_type {};

template<typename A>
struct got_type<A> : std::true_type {
    typedef A type;

template<typename T, T>
struct sig_check : std::true_type {};

template<typename Alias, typename AmbiguitySeed>
struct has_member {
    template<typename C> static char ((&f(decltype(&C::value))))[1];
    template<typename C> static char ((&f(...)))[2];

    //Make sure the member name is consistently spelled the same.
        (sizeof(f<AmbiguitySeed>(0)) == 1)
        , "Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified."

    static bool const value = sizeof(f<Alias>(0)) == 2;

Macros (El Diablo!):


//Check for any member with given name, whether var, func, class, union, enum.
#define CREATE_MEMBER_CHECK(member)                                         \
template<typename T, typename = std::true_type>                             \
struct Alias_##member;                                                      \
template<typename T>                                                        \
struct Alias_##member <                                                     \
    T, std::integral_constant<bool, got_type<decltype(&T::member)>::value>  \
> { static const decltype(&T::member) value; };                             \
struct AmbiguitySeed_##member { char member; };                             \
template<typename T>                                                        \
struct has_member_##member {                                                \
    static const bool value                                                 \
        = has_member<                                                       \
            Alias_##member<ambiguate<T, AmbiguitySeed_##member>>            \
            , Alias_##member<AmbiguitySeed_##member>                        \
        >::value                                                            \
    ;                                                                       \


//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name)                                   \
template<typename T, typename = std::true_type>                             \
struct has_member_var_##var_name : std::false_type {};                      \
template<typename T>                                                        \
struct has_member_var_##var_name<                                           \
    T                                                                       \
    , std::integral_constant<                                               \
        bool                                                                \
        , !std::is_member_function_pointer<decltype(&T::var_name)>::value   \
    >                                                                       \
> : std::true_type {}


//Check for member function with given name AND signature.
#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix)    \
template<typename T, typename = std::true_type>                             \
struct has_member_func_##templ_postfix : std::false_type {};                \
template<typename T>                                                        \
struct has_member_func_##templ_postfix<                                     \
    T, std::integral_constant<                                              \
        bool                                                                \
        , sig_check<func_sig, &T::func_name>::value                         \
    >                                                                       \
> : std::true_type {}


//Check for member class with given name.
#define CREATE_MEMBER_CLASS_CHECK(class_name)               \
template<typename T, typename = std::true_type>             \
struct has_member_class_##class_name : std::false_type {};  \
template<typename T>                                        \
struct has_member_class_##class_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_class<                                    \
            typename got_type<typename T::class_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}


//Check for member union with given name.
#define CREATE_MEMBER_UNION_CHECK(union_name)               \
template<typename T, typename = std::true_type>             \
struct has_member_union_##union_name : std::false_type {};  \
template<typename T>                                        \
struct has_member_union_##union_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_union<                                    \
            typename got_type<typename T::union_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}


//Check for member enum with given name.
#define CREATE_MEMBER_ENUM_CHECK(enum_name)                 \
template<typename T, typename = std::true_type>             \
struct has_member_enum_##enum_name : std::false_type {};    \
template<typename T>                                        \
struct has_member_enum_##enum_name<                         \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_enum<                                     \
            typename got_type<typename T::enum_name>::type  \
        >::value                                            \
    >                                                       \
> : std::true_type {}


//Check for function with given name, any signature.
#define CREATE_MEMBER_FUNC_CHECK(func)          \
template<typename T>                            \
struct has_member_func_##func {                 \
    static const bool value                     \
        = has_member_##func<T>::value           \
        && !has_member_var_##func<T>::value     \
        && !has_member_class_##func<T>::value   \
        && !has_member_union_##func<T>::value   \
        && !has_member_enum_##func<T>::value    \
    ;                                           \


//Create all the checks for one member.  Does NOT include func sig checks.
#define CREATE_MEMBER_CHECKS(member)    \
CREATE_MEMBER_CHECK(member);            \
CREATE_MEMBER_VAR_CHECK(member);        \

Parsing JSON array into java.util.List with Gson

I was able to get the list mapping to work with just using @SerializedName for all fields.. no logic around Type was necessary.

Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data

Here's an example:

1. The JSON

    "name": "Some House",
    "gallery": [
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"

2. Java class with the List

public class FocusArea {

    private String mName;

    private List<ContentImage> mGalleryImages;

3. Java class for the List items

public class ContentImage {

    private String mDescription;

    private String mPhotoUrl;

    // getters/setters ..

4. The Java code that processes the JSON

    for (String key : focusAreaKeys) {

        JsonElement sectionElement = sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);

How do you format a Date/Time in TypeScript?

This worked for me

     * Convert Date type to "YYYY/MM/DD" string 
     * - AKA ISO format?
     * - It's logical and sortable :)
     * - 20200227
     * @param Date eg. new Date()
    static DateToYYYYMMDD(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
        return DS

You can certainly add HH:MM something like this...

    static DateToYYYYMMDD_HHMM(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
            + ' ' + ('0' + Date.getHours()).slice(-2)
            + ':' + ('0' + Date.getMinutes()).slice(-2)
        return DS

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url =
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!

Further information

You may also be interested in reading an answer to a related question.


The solution I found to work the best was using a subquery like this:

    col1, col2, 
        SELECT COUNT(*) 
        FROM Table1
        WHERE col1 = t1.col1
        AND col2 = t1.col2
        AND col3 > t1.col3
    ) AS intRow
FROM Table1 t1

The PARTITION BY columns just get compared with '=' and separated by AND. The ORDER BY columns would be compared with '<' or '>', and separated by OR.

I've found this to be very flexible, even if it is a little bit costly.

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

get data from mysql database to use in javascript

To do with javascript you could do something like this:

<script type="Text/javascript">
var text = <?= $text_from_db; ?>

Then you can use whatever you want in your javascript to put the text var into the textbox.

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

T-SQL substring - separating first and last name

I think below query will be helpful to split FirstName and LastName from FullName even if there is only FirstName. For example: 'Philip John' can be split into Philip and John. But if there is only Philip, because of the charIndex of Space is 0, it will only give you ''.

Try the below one.

declare @FullName varchar(100)='Philp John'

    LTRIM(RTRIM(SUBSTRING(@FullName, 0, CHARINDEX(' ', @FullName+' ')))) As FirstName
,   LTRIM(RTRIM(SUBSTRING(@FullName, CHARINDEX(' ', @FullName+' ')+1, 8000)))As LastName

Hope this will help you. :)

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.

Then just replace 1140px with 98% of the screen width.

@media (min-width: 1200px) {
  .container {
    width: 1140px;

enter image description here

After editing

@media (min-width: 1200px) {
  .container {
    width: 98%;

enter image description here Save and restart your notebook


Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.

If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir


Adjust UILabel height to text

You can also use sizeThatFits function.

For example:


What is mutex and semaphore in Java ? What is the main difference?

Mutex is binary semaphore. It must be initialized with 1, so that the First Come First Serve principle is met. This brings us to the other special property of each mutex: the one who did down, must be the one who does up. Ergo we have obtained mutual exclusion over some resource.

Now you could see that a mutex is a special case of general semaphore.

How to get a responsive button in bootstrap 3

In Bootstrap, the .btn class has a white-space: nowrap; property, making it so that the button text won't wrap. So, after setting that to normal, and giving the button a width, the text should wrap to the next line if the text would exceed the set width.

#new-board-btn {
    white-space: normal;

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        styles.put("date_style", style);
        return styles;

you can also use methods to do repetitive tasks while creating styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        return style;

then, in your "main" code, set the style from the styles map you have.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );

Android Layout Weight

weight values 0-1 share distribution of available space (after setting layout_width="0px") in proportion to the weight value. View elements with weight not specified (no weight entry) get weight 0 which means they get no expansion.

A simple alternative with no weight entries needed is to attach marquee to a view with text which tells it to expand from minimum needed for the text (wrap_content) to space available EditText: android:layout_width="wrap_content" android:ellipsize="marquee"

if statements matching multiple values

I had the same problem but solved it with a switch statement switch(a value you are switching on) { case 1: the code you want to happen; case 2: the code you want to happen; default: return a value }

Converting String to "Character" array in Java

Why not write a little method yourself

public Character[] toCharacterArray( String s ) {

   if ( s == null ) {
     return null;

   int len = s.length();
   Character[] array = new Character[len];
   for (int i = 0; i < len ; i++) {
      Character(char) is deprecated since Java SE 9 & JDK 9
      array[i] = new Character(s.charAt(i));
      array[i] = s.charAt(i);

   return array;

format a number with commas and decimals in C# ( MVC3)

Your question is not very clear but this should achieve what you are trying to do:

decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");

Then formatted will contain: 3,494,309,432,324.00

What's the "average" requests per second for a production web application?

OpenStreetMap seems to have 10-20 per second

Wikipedia seems to be 30000 to 70000 per second spread over 300 servers (100 to 200 requests per second per machine, most of which is caches)

Geograph is getting 7000 images per week (1 upload per 95 seconds)

C++ Singleton design pattern

I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:


class DoNotCopy
    DoNotCopy(void) = default;
    DoNotCopy(const DoNotCopy&) = delete;
    DoNotCopy& operator=(const DoNotCopy&) = delete;

class DoNotMove
    DoNotMove(void) = default;
    DoNotMove(DoNotMove&&) = delete;
    DoNotMove& operator=(DoNotMove&&) = delete;

class DoNotCopyMove : public DoNotCopy,
    public DoNotMove
    DoNotCopyMove(void) = default;

template<class T>
class Singleton : public DoNotCopyMove
    static T& Instance(void)
        static T instance;
        return instance;

    Singleton(void) = default;

class Logger final: public Singleton<Logger>
    void log(const std::string& str) { std::cout << str << std::endl; }

int main()

The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).

TypeError: $.browser is undefined

I did solved using this jquery for Github

<script src=""></script>

Please Refer this link for more info.

make div's height expand with its content

Have you tried the traditional way? give the main container height:auto


I have used this and it worked most of the times with me.

How can I trigger a Bootstrap modal programmatically?

You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:


and hide with:


Data binding in React

There are actually people wanting to write with two-way binding, but React does not work in that way.

That's true, there are people who want to write with two-way data binding. And there's nothing fundamentally wrong with React preventing them from doing so. I wouldn't recommend them to use deprecated React mixin for that, though. Because it looks so much better with some third-party packages.

import { LinkedComponent } from 'valuelink'

class Test extends LinkedComponent {
    state = { a : "Hi there! I'm databinding demo!" };

        // Bind all state members...
        const { a } = this.linkAll();

        // Then, go ahead. As easy as that.
        return (
             <input type="text" ...a.props />

The thing is that the two-way data binding is the design pattern in React. Here's my article with a 5-minute explanation on how it works

How to make an ng-click event conditional?

It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.

But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.

Another way is to use lazy evaluation of expressions like isDisabled || action() so action wouold not be called if isDisabled is true.

Here goes both solutions:

PHP - Debugging Curl

To just get the info of a CURL request do this:

$response = curl_exec($ch);

$info = curl_getinfo($ch);

How do I round a double to two decimal places in Java?

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");

XAMPP: Couldn't start Apache (Windows 10)

Actually, by default IIS (Microsoft, .NET, etc.) is installed.

  • Go to Control Panel
  • Turn Windows features on or off...
  • Under (IIS) Internet Information Services, uncheck the (WWWS) world wide web services.
  • Click OK.

This could be a permanent solution. :)

Performance differences between ArrayList and LinkedList

Even they seem to identical(same implemented inteface List - non thread-safe),they give different results in terms of performance in add/delete and searching time and consuming memory (LinkedList consumes more).

LinkedLists can be used if you use highly insertion/deletion with performance O(1). ArrayLists can be used if you use direct access operations with performance O(1)

This code may make clear of these comments and you can try to understand performance results. (Sorry for boiler plate code)

public class Test {

    private static Random rnd;

    static {
        rnd = new Random();

    static List<String> testArrayList;
    static List<String> testLinkedList;
    public static final int COUNT_OBJ = 2000000;

    public static void main(String[] args) {
        testArrayList = new ArrayList<>();
        testLinkedList = new LinkedList<>();


        checkInsertionPerformance(testLinkedList);  //O(1)
        checkInsertionPerformance(testArrayList);   //O(1) -> O(n)

        checkPerformanceForFinding(testArrayList);  // O(1)
        checkPerformanceForFinding(testLinkedList); // O(n)


    public static void insertSomeDummyData(List<String> list) {
        for (int i = COUNT_OBJ; i-- > 0; ) {
            list.add(new String("" + i));

    public static void checkInsertionPerformance(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
            list.add(rndIndex, "test");
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at insertion:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));

    public static void checkPerformanceForFinding(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at searching:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));



Calling a class method raises a TypeError in Python

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document '', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
    AS BIT)
    return @result

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

How to convert a 3D point into 2D perspective projection?

All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.

I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.

Access elements in json object like an array

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

Check this fully functional directive for MEAN.JS (Angular.js, bootstrap, Express.js and MongoDb)

Based on @Blackhole ´s response, we just finished it to be used with mongodb and express.

It will allow you to save and load dates from a mongoose connector

Hope it Helps!!

  function(dateFilter) {
    return {
      require: 'ngModel',
      template: '<input type="date" class="form-control"></input>',
      replace: true,
      link: function(scope, elm, attrs, ngModelCtrl) {
        ngModelCtrl.$formatters.unshift(function (modelValue) {
          return dateFilter(modelValue, 'yyyy-MM-dd');

           return angular.toJson(modelValue,true)



div(date-input, ng-model="modelDate")

ObjectiveC Parse Integer from String

NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];

_returnedArguments is an array of NSStrings which the UITextField text property is expecting. No need to convert.

Syntax error:

[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];

If your _appDelegate has a passwordField property, then you can set the text using the following

[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];

Java multiline string

I got a bit annoyed with reading that multiline syntax is indeed been planned for jdk7 (after about how many decades of java existence?). Funnily, there is not even yet a readAll() function for reading the complete contents of a file (from jdk7 only, huhh), so the code below reads single lines.

  MakeMultiline v1.0 (2010) - Free to use and copy.

  Small gadget to turn text blobs into one java string literal
  (doing the split in lines, adding \n at each end and enclosing
  in double quotes). Does escape quotes encountered in the text blob.

  Useful for working around missing multiline string syntax in java
  prior jdk7. Use with:

     java MakeMultiline "    "
     java MakeMultiline "    " mytextfile.txt


class MakeMultiline {
  public static void main(String[] args) {
    try {
      // args[0]: indent
      // args[1]: filename to read (optional; stdin if not given)
      // Beware the nmb of newlines at the end when using stdin!

      String indent = (args.length > 0 ? args[0] : "");
      FileReader fr = null; BufferedReader br;
      if (args.length > 1)
        { fr =  new FileReader(args[1]); br = new BufferedReader(fr); }
        { br = new BufferedReader(new InputStreamReader(; }
      String s; String res = "";
      while((s = br.readLine()) != null) {
        if (res.length() > 0) res += " +\n";
        res += indent + "\"" + s.replace("\"", "\\\"") + "\\n\"";
      br.close(); if (fr != null) fr.close();
      System.out.println(res + ";");
    catch(Exception e) {
      System.out.println("Exception: " + e);

This was the quickest solution for me. (2010-01-27)

Variably modified array at file scope

As it is already explained in other answers, const in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum as a real constant in C:

enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = { 
  1, 2, 3, 4

Getting multiple selected checkbox values in a string in javascript and PHP

This code work fine for me, Here i contvert array to string with ~ sign

    <input type="checkbox" value="created" name="today_check"><strong>&nbsp;Created&nbsp;&nbsp;</strong>
    <input type="checkbox" value="modified" name="today_check"><strong>&nbsp;Modified&nbsp;</strong>    
 <a class="get_tody_btn">Submit</a>

<script type="text/javascript">
            var ck_string = "";
            $.each($("input[name='today_check']:checked"), function(){  
                ck_string += "~"+$(this).val();  
            if (ck_string ){
                ck_string = ck_string .substring(1);
                alert('Please choose atleast one value.');


Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

Redirect all output to file in Bash

It might be the standard error. You can redirect it:

... > out.txt 2>&1

Login with facebook android sdk app crash API 4

The official answer from Facebook (


The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Error occurred during initialization of boot layer FindException: Module not found

check your project build in jdk 9 or not above that eclipse is having some issues with the modules. Change it to jdk 9 then it will run fine

Difference between Destroy and Delete

A lot of answers already; wanted to jump on with a bit more.


For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

The delete verbage works differently for ActiveRecord::Association.has_many and ActiveRecord::Base. For the latter, delete will execute SQL DELETE and bypass all validations/callbacks. The former will be executed based on the :dependent option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete and not delete_all

dependent: :destroy Example:

class Parent < ApplicationRecord
   has_many :children,
     before_remove: -> (_) { puts "before_remove callback" },
     dependent: :destroy

class Child < ApplicationRecord
   belongs_to :parent

   before_destroy -> { puts "before_destroy callback" }

> child.delete                            # Ran without callbacks
Child Destroy (99.6ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 21]]

> parent.children.delete(other_child)     # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 22]]

> parent.children.delete_all              # Ran without callbacks
Child Destroy (1.0ms)  DELETE FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 1]]

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first. This caused an error:

<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>

This is right, works:

<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>

So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.

Selecting pandas column by location

Two approaches that come to mind:

>>> df
          A         B         C         D
0  0.424634  1.716633  0.282734  2.086944
1 -1.325816  2.056277  2.583704 -0.776403
2  1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025  1.325853 -2.513373
4  1.366180 -1.265185 -2.184617  0.881514
>>> df.iloc[:, 2]
0    0.282734
1    2.583704
2   -1.560583
3    1.325853
4   -2.184617
Name: C
>>> df[df.columns[2]]
0    0.282734
1    2.583704
2   -1.560583
3    1.325853
4   -2.184617
Name: C

Edit: The original answer suggested the use of df.ix[:,2] but this function is now deprecated. Users should switch to df.iloc[:,2].

What is the difference between Sublime text and Github's Atom

In addition to the points from prior answers, it's worth clarifying the differences between these two products from the perspective of choices made in their development.

Sublime is binary compiled for the platform. Its core is written in C/C++ and a number of its features are implemented in Python, which is also the language used for extending it. Atom is written in Node.js/Coffeescript and runs under webkit, with Coffeescript being the extension language. Though similar in UI and UX, Sublime performs significantly better than Atom especially in "heavy lifting" like working with large files, complex SnR or plugins that do heavy processing on files/buffers. Though I expect improvements in Atom as it matures, design & platform choices limit performance.

The "closed" part of Sublime includes the API and UI. Apart from skins/themes and colourisers, the API currently makes it difficult to modify other aspects of the UI. For example, Sublime plugins can't interact with the sidebar, control or draw on the editing area (except in some limited ways eg. in the gutter) or manipulate the statusbar beyond basic text. Atom's "closed" part is unknown at the moment, but I get the sense it's smaller. Atom has a richer API (though poorly documented at present) with the design goal of allowing greater control of its UI. Being closely coupled with webkit offers numerous capabilities for UI feature enhancements not presently possible with Sublime. However, Sublime's extensions perform closer to native, so those that perform compute-intensive, highly repetitive or complex text manipulations in large buffers are feasible in Sublime.

Since more of Atom will be open, Github open-sourced Atom on May 6th. As a result it's likely that support and pace of development will be rapid. By contrast, Sublime's development has slowed significantly of late - but it's not dead. In particular there are a number of bugs, many quite trivial, that haven't been fixed by the developer. None are showstopping imo, but if you want something in rapid development with regular bugfixing and enhancements, Sublime will frustrate. That said, installable Atom packages for Windows and Linux are yet to be released and activity on the codebase seems to have cooled in the weeks before and since the announcement, according to Github's stats.

In terms of IDE functions, from a webdev perspective Atom will allow extensions to the point of approaching products like Webstorm, though none have appeared yet. It remains to be seen how Atom will perform with such "heavy" extensions, since the editor natively feels sluggish. Due to restrictions in the API and lack of underlying webkit, Sublime won't allow this level of UI customisation although the developer may extend the API to support such features in future. Again, Sublime's underlying performance allows for things that involve computational grunt; ST3's symbol indexing being an example that performs well even with big projects. And though Atom's UI is certainly modelled upon Sublime, some refinements are noticeably missing, such as Sublime's learning panels and tab-complete popups which weight the defaults in accordance with those you most use.

I see these products as complementary. The fact that they share similar visuals and keystrokes just adds to the fact. There will be situations where the use of either has advantages. Presently, Sublime is a mature product with feature parity across all three platforms, and a rich set of plugins. Atom is the new kid whose features will rapidly grow; it doesn't feel production ready just yet and there are concerns in the area of performance.

[Update/Edit: May 18, 2015]

A note about improvements to these two editors since the time of writing the above.

In addition to bugfixes and improvements to its core, Atom has experienced a rapid growth in third-party extensions, with autocomplete-plus becoming part of the standard Atom distribution. Extension quality varies widely and a particular irritation is the frequency by which unstable third party packages can crash the editor. Within the last year, Atom has moved to using React by way of shifting reflow/repaint activity to the GPU for performance reasons, significantly improving the responsiveness of the UI for typical editing actions (scrolling, cursor movement etc.). While this has markedly improved the feel of the editor, it still feels cumbersome for CPU intensive tasks as described above, and is still slow in startup. Apart from performance improvements, Atom feels significantly more stable across the board.

Development of Sublime has picked up again since Jan 2015, with bugfixes, some minor new features (tooltip API, build system improvements) and a major development in the form of a new yaml-based .sublime-syntax definition (to eventually replace the old xml .tmLanguage). Together with a custom regex engine which replaces Onigurama, the new system offers more potential for precise regex matching, is significantly faster (up to 4x) and can perform multiple matches in parallel. Apart from colouring syntax, Sublime uses these components for symbol indexing (goto definition etc.) and other language-aware features. In addition to further speeding up Sublime, particularly for large files, this feature should open up the potential for performant language-specific features such as code-refactoring etc.. Further 'big developments' are promised, though the author remains, as ever, tight lipped about them.

Storing and Retrieving ArrayList values from hashmap

You can use like this(Though the random number generator logic is not upto the mark)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);

public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
    map.put(name, fruit);


grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

Cannot access a disposed object - How to fix?

You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?

If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.

How do I convert between big-endian and little-endian values in C++?

Simply put:

#include <climits>

template <typename T>
T swap_endian(T u)
    static_assert (CHAR_BIT == 8, "CHAR_BIT != 8");

        T u;
        unsigned char u8[sizeof(T)];
    } source, dest;

    source.u = u;

    for (size_t k = 0; k < sizeof(T); k++)
        dest.u8[k] = source.u8[sizeof(T) - k - 1];

    return dest.u;

usage: swap_endian<uint32_t>(42).

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x =;

Then you can spy on :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...

How do I revert all local changes in Git managed project to previous state?

Look into git-reflog. It will list all the states it remembers (default is 30 days), and you can simply checkout the one you want. For example:

$ git init > /dev/null
$ touch a
$ git add .
$ git commit -m"Add file a" > /dev/null
$ echo 'foo' >> a
$ git commit -a -m"Append foo to a" > /dev/null
$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
$ git reset --hard HEAD^^ > /dev/null
$ cat a
$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
$ cat a

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>


On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

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

git rev-parse --show-toplevel

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


Show the absolute path of the top-level directory.

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

git rev-parse --git-dir

That would give the path of the .git directory.

The OP mentions:

git rev-parse --show-prefix

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

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

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

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

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

Group dataframe and get sum AND count?

Just in case you were wondering how to rename columns during aggregation, here's how for

pandas >= 0.25: Named Aggregation

df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')


df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))

                       MySum  MyCount
Company Name                       
Vifor Pharma UK Ltd  4207.93        5

Regex match one of two words

This will do:


to exclude from captured strings (e.g. $1,$2):


How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text =;
    onChange(id, text);

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });

  const fields = => (

  return (
      <pre>{JSON.stringify(values, null, 2)}</pre>

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;

Original - pre-hooks version:

class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  handleChange(event) {_x000D_
    const text =;_x000D_
    this.props.onChange(, text);_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    this.state = {};_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  render() {_x000D_
    const fields = => (_x000D_
    return (_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
  return <FormEditor fields={fields} />;_x000D_
ReactDOM.render(<App />, document.body);

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;

Bootstrap 4 Breakpoints demo

What are the JavaScript KeyCodes?

One possible answer will be given when you run this snippet.

for (var i = 0; i < 250; i++) {_x000D_
  document.write('<tr><td>' + i + '</td><td>' + String.fromCharCode(i) + '</td></tr>')_x000D_
td {_x000D_
  border: solid 1px;_x000D_
  padding: 1px 12px;_x000D_
  text-align: right;_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
* {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.1em;_x000D_

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  /* ...and now for the proper property */
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
a:hover { color:red; background:yellow; }

Demo here

Difference between array_map, array_walk and array_filter

  • Changing Values:
  • Array Keys Access:
  • Return Value:
    • array_map returns a new array, array_walk only returns true. Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk.
  • Iterating Multiple Arrays:
    • array_map also can receive an arbitrary number of arrays and it can iterate over them in parallel, while array_walk operates only on one.
  • Passing Arbitrary Data to Callback:
    • array_walk can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced).
  • Length of Returned Array:
    • The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function. It does preserve the keys.



$origarray1 = array(2.4, 2.6, 3.5);
$origarray2 = array(2.4, 2.6, 3.5);

print_r(array_map('floor', $origarray1)); // $origarray1 stays the same

// changes $origarray2
array_walk($origarray2, function (&$v, $k) { $v = floor($v); }); 

// this is a more proper use of array_walk
array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; });

// array_map accepts several arrays
    array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2)

// select only elements that are > 2.5
    array_filter($origarray1, function ($a) { return $a > 2.5; })



    [0] => 2
    [1] => 2
    [2] => 3
    [0] => 2
    [1] => 2
    [2] => 3
0 => 2.4
1 => 2.6
2 => 3.5
    [0] => 4.8
    [1] => 5.2
    [2] => 10.5
    [1] => 2.6
    [2] => 3.5

Adding script tag to React/JSX

I tried to edit the accepted answer by @Alex McMillan but it won't let me so heres a separate answer where your able to get the value of the library your loading in. A very important distinction that people asked for and I needed for my implementation with stripe.js.


import { useState, useEffect } from 'react'

export const useScript = (url, name) => {

  const [lib, setLib] = useState({})

  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = true
    script.onload = () => setLib({ [name]: window[name] })


    return () => {
  }, [url])

  return lib


usage looks like

const PaymentCard = (props) => {
  const { Stripe } = useScript('', 'Stripe')

NOTE: Saving the library inside an object because often times the library is a function and React will execute the function when storing in state to check for changes -- which will break libs (like Stripe) that expect to be called with specific args -- so we store that in an object to hide that from React and protect library functions from being called.

Unzipping files in Python

If you want to do it in shell, instead of writing code.

 python3 -m zipfile -e myfiles/ is the zip archive and myfiles is the path to extract the files.

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 END as mesto_utovara

Sum of Numbers C++

try this:

#include <iostream>
using namespace std;

int main()
    int positiveInteger;
    int startingNumber = 1;

    cout << "Please input an integer upto 100." << endl;

    cin >> positiveInteger;

    int result = 0;
    for (int i=startingNumber; i <= positiveInteger; i++)
        result += i;
        cout << result;

    cout << result;

    return 0;


Converting HTML to plain text in PHP for e-mail

Use html2text (example HTML to text), licensed under the Eclipse Public License. It uses PHP's DOM methods to load from HTML, and then iterates over the resulting DOM to extract plain text. Usage:

// when installed using the Composer package
$text = Html2Text\Html2Text::convert($html);

// usage when installed using html2text.php
$text = convert_html_to_text($html);

Although incomplete, it is open source and contributions are welcome.

Issues with other conversion scripts:

  • Since html2text (GPL) is not EPL-compatible.
  • lkessler's link (attribution) is incompatible with most open source licenses.

Split long commands in multiple lines through Windows batch file

Multiple commands can be put in parenthesis and spread over numerous lines; so something like echo hi && echo hello can be put like this:

( echo hi
  echo hello )

Also variables can help:

if exist %AFILEPATH% (
  start "" /b %AFILEPATH% -option C:\PATH\TO\SETTING...
) else (

Also I noticed with carets (^) that the if conditionals liked them to follow only if a space was present:

if exist ^

Multiple IF statements between number ranges

standalone one cell solution based on VLOOKUP

US syntax:

        IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
 {{(TRANSPOSE({{{0;   "Less than 500"},
               {500;  "Between 500 and 1000"}},
              {{1000; "Between 1000 and 1500"},
               {1500; "Between 1500 and 2000"}}}))}}, 2)),)), )

EU syntax:

        IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
 {{(TRANSPOSE({{{0;   "Less than 500"}\
               {500;  "Between 500 and 1000"}}\
              {{1000; "Between 1000 and 1500"}\
               {1500; "Between 1500 and 2000"}}}))}}; 2));)); )


Get the selected option id with jQuery

$('#my_select option:selected').attr('id');

What is the equivalent of bigint in C#?

For most of the cases it is long(int64) in c#

Oracle query to fetch column names

I find this one useful in Oracle:

    all_tab_columns atc,
        object_name like 'GL_JE%'
        AND owner = 'GL'
        AND object_type in ('TABLE','VIEW')   
    ) obj
    atc.table_name = obj.object_name

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for in that folder.

Callback after all asynchronous forEach callbacks are completed

It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:

var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);


4000 started
2000 started
1: 2000
0: 4000

If we check for index === array.length - 1, callback will be called upon completion of first iteration, whilst first element is still pending!

To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:


Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

How to close <img> tag properly?

The best use of tags you should use:

<img src="" alt=""/>

Also you can use in HTML5:

<img src="" alt="">

These two are completely valid in HTML5 Pick one of them and stick with that.

Where does Visual Studio look for C++ header files?

There seems to be a bug in Visual Studio 2015 community. For a 64-bit project, the include folder isn't found unless it's in the win32 bit configuration Additional Include Folders list.

How do you use youtube-dl to download live streams (that are live)?

Before, this could be downloaded with streamlink but YouTube changed HLS rewinding with DASH. Therefore the way to do it below (that Prashant Adlinge commented) no longer works for YouTube:

streamlink --hls-live-restart STREAMURL best

More info here

Python vs. Java performance (runtime speed)

There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.

How to use filter, map, and reduce in Python 3

from functools import reduce

def f(x):
    return x % 2 != 0 and x % 3 != 0

print(*filter(f, range(2, 25)))
#[5, 7, 11, 13, 17, 19, 23]

def cube(x):
    return x**3
print(*map(cube, range(1, 11)))
#[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

def add(x,y):
    return x+y

reduce(add, range(1, 11))

It works as is. To get the output of map use * or list

Convert an object to an XML string

Here are conversion method for both ways. this = instance of your class

public string ToXML()
        using(var stringwriter = new System.IO.StringWriter())
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(stringwriter, this);
            return stringwriter.ToString();

 public static YourClass LoadFromXMLString(string xmlText)
        using(var stringReader = new System.IO.StringReader(xmlText))
            var serializer = new XmlSerializer(typeof(YourClass ));
            return serializer.Deserialize(stringReader) as YourClass ;

Convert from MySQL datetime to another format with PHP

An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.

If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.

Where is adb.exe in windows 10 located?

If you just want to run adb command. Open command prompt and run following command:

C:\Users\<user_name>\AppData\Local\Android\sdk\platform-tools\adb devices

NOTE: Make sure to replace <user_name> in above command.

Non-alphanumeric list order from os.listdir()

ls by default previews the files sorted by name. (ls options can be used to sort by date, size, ...)

files = list(os.popen("ls"))
files = [file.strip("\n") for file in files]

Using ls would have much better performance when the directory contains so many files.

How can I provide multiple conditions for data trigger in WPF?


If you wanna implement the AND logic, you should use MultiTrigger, here is an example:

Suppose we want to do some actions if the property Text="" (empty string) AND IsKeyboardFocused="False", then your code should look like the following:

        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
            <!-- Your actions here -->

If you wanna implement the OR logic, there are couple of ways, and it depends on what you try to do:

The first option is to use multiple Triggers.
So, suppose you wanna do something if either Text="" OR IsKeyboardFocused="False",
then your code should look something like this:

<Trigger Property="IsEnabled" Value="false">
    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="BorderBrush" TargetName="border" 
            Value="{StaticResource TextBox.MouseOver.Border}"/>

But the problem in this is what will I do if i wanna do something if either Text ISN'T null OR IsKeyboard="True"? This can be achieved by the second approach:
Recall De Morgan's rule, that says !(!x && !y) = x || y.
So we'll use it to solve the previous problem, by writing a multi trigger that it's triggered when Text="" and IsKeyboard="True", and we'll do our actions in EXIT ACTIONS, like this:

        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
        <!-- Do something here -->

Uncaught SyntaxError: Unexpected token u in JSON at position 0

For me, that happened because I had an empty component in my page -

<script type="text/x-magento-init">
   ".page.messages": {
       "Magento_Ui/js/core/app": []        

Deleting this piece of code resolved the issue.

How to read single Excel cell value

Please try this. Maybe this could help you. It works for me.

string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//_row,_column your column & row number 
//eg: string sValue = (sheet.Cells[i + 9, 12] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//sValue has your value

Regex for Comma delimited list

Match duplicate comma-delimited items:



This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.



How do you use math.random to generate random ints?

Cast abc to an integer.


WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

Judging from the messages you send via Socket.IO socket.emit('greet', { hello: 'Hey, Mr.Client!' });, it seems that you are using the hackathon-starter boilerplate. If so, the issue might be that express-status-monitor module is creating its own instance, as per:

You can either:

  1. Remove that module
  2. Pass in your instance and port as websocket when you create the expressStatusMonitor instance like below:

    const server = require('http').Server(app);
    const io = require('')(server);
    app.use(expressStatusMonitor({ websocket: io, port: app.get('port') })); 

get and set in TypeScript

If you are looking for way to use get and set on any object (not a class) Proxy may be usefull:

const target = {
  message1: "hello",
  message2: "everyone"

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    return Reflect.get(...arguments);

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world

Note: be aware that this is new api not supported and required polifill for older browsers

How do I get time of a Python program's execution?

There is a timeit module which can be used to time the execution times of Python code.

It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.

Can I call a function of a shell script from another shell script?

The problem

The currenly accepted answer works only under important condition. Given...


function func1 {  
   echo "Hello $1"




source ./
func1 World

this works only if the is executed from within the same directory where the is located. Ie. if the current working path of shell is /foo, the attempt to run command

cd /foo

prints error:

/foo/bar/ line 4: func1: command not found

That's because the source ./ is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run

(cd /foo/bar; ./

More generic solution



function func1 {  
   echo "Hello $1"




source $(dirname "$0")/

func1 World


cd /foo


Hello World

How it works

  • $0 returns relative or absolute path to the executed script
  • dirname returns relative path to directory, where the $0 script exists
  • $( dirname "$0" ) the dirname "$0" command returns relative path to directory of executed script, which is then used as argument for source command
  • in "", / just appends the name of imported shell script
  • source loads content of specified file into current shell

How do I get the App version and build number using Swift?

if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            self.lblAppVersionValue.text = version

Collision resolution in Java HashMap

When multiple keys end up in same hash code which is present in same bucket. When the same key has different values then the old value will be replaced with new value.

Liked list converted to balanced Binary tree from java 8 version on wards in worst case scenario.

Collision happen when 2 distinct keys generate the same hashcode() value. When there are more collisions then there it will leads to worst performance of hashmap.

Objects which are are equal according to the equals method must return the same hashCode value. When both objects return the same has code then they will be moved into the same bucket.

T-SQL Subquery Max(Date) and Joins

Try this:

Select *,
    Price = (Select top 1 Price 
             From MyPrices 
             where PartID = mp.PartID 
             order by PriceDate desc
from MyParts mp

How to locate the Path of the current project directory in Java (IDE)?

What about System.getProperty("user.dir")? It'll give you the working directory from where your program was launched.

See System Properties from the Java Tutorial for an overview of Java's System Properties.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

Good article here: Cross-domain communication with iframes

Also you can directly set document.domain the same in both frames (even

document.domain = document.domain;

code has sense because resets port to null), but this trick is not general-purpose.

How to set a text box for inputing password in winforms?

Just set the property of textbox that is PasswordChar and set the * as a property of textbox. That will work for password.

  passwordtextbox.PasswordChar = '*';

where passwordtextbox is the text box name.

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:



table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

If statement in select (ORACLE)

    --  <add any columns to outer select from inner query> 
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 WHERE... -- optional --

Automatically size JPanel inside JFrame

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());

GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

Set initial value in datepicker with jquery?

Use this code it will help you.


<input type="text" id="txtFromDate" class="datepicker calendar-icon" placeholder="From Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
        <input type="text" id="txtToDate" class="datepicker calendar-icon" placeholder="To Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">

function InitializeDate() {
    var date = new Date();
    var dd = date.getDate();             
    var mm = date.getMonth() + 1;
    var yyyy = date.getFullYear();

    var ToDate = mm + '/' + dd + '/' + yyyy;
    var FromDate = mm + '/01/' + yyyy;
    $('#txtToDate').datepicker('setDate', ToDate);
    $('#txtFromDate').datepicker('setDate', FromDate);

What is the http-header "X-XSS-Protection"?

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

In Python, can I call the main() of an imported module?

Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.

In the version where you use argparse, you need to have this line in the main body.

args = parser.parse_args(args)

Normally when you are using argparse just in a script you just write

args = parser.parse_args()

and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.

Here is an example

import argparse
import sys

def x(x_center, y_center):
    print "X center:", x_center
    print "Y center:", y_center

def main(args):
    parser = argparse.ArgumentParser(description="Do something.")
    parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
    parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
    args = parser.parse_args(args)
    x(args.xcenter, args.ycenter)

if __name__ == '__main__':

Assuming you named this To run it you can either do any of these from the command line

python ./ -x 8
python ./ -x 8 -y 2
python ./ 

which returns respectively

X center: 8.0
Y center: 4


X center: 8.0
Y center: 2.0


X center: 2
Y center: 4

Or if you want to run from another python script you can do

import mytest

which returns

X center: 7.0
Y center: 6.0

Excel: Searching for multiple terms in a cell

This will do it for you:


Given this function in the column to the right of the names (which are in column C), the result is:

Gingrich    1
Obama       1

How can I view all historical changes to a file in SVN

Thanks, Bendin. I like your solution very much.

I changed it to work in reverse order, showing most recent changes first. Which is important with long standing code, maintained over several years. I usually pipe it into more.

svnhistory |more

I added -r to the sort. I removed spec. handling for 'first record'. It is it will error out on the last entry, as there is nothing to diff it with. Though I am living with it because I never get down that far.


# history_of_file                                                              
# Bendin on Stack Overflow:          
#   Outputs the full history of a given file as a sequence of                  
#   logentry/diff pairs.  The first revision of the file is emitted as         
#   full text since there's not previous version to compare it to.             
# Dlink                                                                        
#   Made to work in reverse order                                              

function history_of_file() {
    url=$1 # current url of file                                               
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
        while read r
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD

history_of_file $1

CMake does not find Visual C++ compiler

Menu ? Visual Studio 2015 ? MSBuild Command Prompt for Visual Studio 2015. Then CMake can find cl.exe.

set PATH="c:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64\";%PATH%

Change the upper path to where your Windows SDK is installed.

CMake can find rc.exe.

cd to the path of CMakeLists.txt and do:

md .build
cd .build
cmake .. -G "Visual Studio 14 2015 Win64" -DCMAKE_BUILD_TYPE=Release
cmake --build .

The param after -G should be fetched by CMake. Use --help; you may or may not have the generator.

Restrict varchar() column to specific values?

Personally, I'd code it as tinyint and:

  • Either: change it to text on the client, check constraint between 1 and 4
  • Or: use a lookup table with a foreign key


  • It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.

  • What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.

  • Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.

limit text length in php and provide 'Read more' link

This worked for me.

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
echo $string;

Thanks @webbiedave

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

Mapping list in Yaml to list of objects in Spring Boot

I tried 2 solutions, both work.



      username: eXvn817zDinHun2QLQ==
      password: IP2qP+BQfWKJMVeY7Q==
      username: uwJlOl/jP6/fZLMm0w==
      password: IP2qP+BQKJLIMVeY7Q==

@ConfigurationProperties(prefix = "available-users-list")
public class LoginInfos {
    private List<LoginInfo> configurations;

    public static class LoginInfo {
        private String username;
        private String password;

List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();



available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'


String testList;

ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);

Safe navigation operator (?.) or (!.) and null property paths

Another alternative that uses an external library is _.has() from Lodash.


_.has(a, 'b.c')

is equal to

(a && a.b && a.b.c)

EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.

Wait some seconds without blocking UI execution

If possible, the preferred approach should be using an asynchronous way or a second thread.

If this isn't possible or wanted, using any implementation of DoEvents() is a bad idea, since it may cause problems Possible problems with DoEvents. This is mostly about DoEvents with Winforms but the possible pitfalls in WPF are the same.

Then putting a frame on the Dispatcher with the wanted sleep time can be used:

using System;
using System.Threading;
using System.Windows.Threading;

public static void NonBlockingSleep(int timeInMilliseconds)
    DispatcherFrame df = new DispatcherFrame();

    new Thread((ThreadStart)(() =>
        df.Continue = false;



ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

Remove empty array elements

You can just do


array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.

The other option is doing

array_diff($array, array(''))

which will remove elements with values NULL, '' and FALSE.

Hope this helps :)


Here is an example.

$a = array(0, '0', NULL, FALSE, '', array());

// array()

var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());

var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())

To sum up:

  • 0 or '0' will remove 0 and '0'
  • NULL, FALSE or '' will remove NULL, FALSE and ''

How to use a DataAdapter with stored procedure and parameter

SqlConnection con = new SqlConnection(@"Some Connection String");//connection object
SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);//SqlDataAdapter class object
da.SelectCommand.CommandType = CommandType.StoredProcedure; //command sype
da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123; //pass perametter
DataTable dt = new DataTable();  //dataset class object
da.Fill(dt); //call the stored producer

How can I join on a stored procedure?

Why not just performing the calculation in your SQL?

  , t.CarPlateNumber
  , t.CarColor
  , t.Sex
  , t.SSNO
  , t.Phone
  , t.Memo
  , u.UnitNumber
  , p.PropertyName
  , trans.TenantBalance
FROM tblTenant t
     LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
     LEFT JOIN tblProperty p ON u.PropertyID = p.ID
       SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
       FROM tblTenant tenant
            LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
       GROUP BY tenant.ID
     ) trans ON trans.ID = t.ID
  , t.CarPlateNumber

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.

Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

Why can't Python parse this JSON data?

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

How to get just numeric part of CSS property with jQuery?

If it's just for "px" you can also use:

$(this).css('marginBottom').slice(0, -2);

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos( * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.

Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()

What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

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

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))

Hope this helps, not the best way I am sure, and Access should have had this built in.

Does a TCP socket connection have a "keep alive"?

For Windows according to Microsoft docs

  • KeepAliveTime (REG_DWORD, milliseconds, by default is not set which means 7,200,000,000 = 2 hours) - analogue to tcp_keepalive_time
  • KeepAliveInterval (REG_DWORD, milliseconds, by default is not set which means 1,000 = 1 second) - analogue to tcp_keepalive_intvl
  • Since Windows Vista there is no analogue to tcp_keepalive_probes, value is fixed to 10 and cannot be changed

How to avoid reverse engineering of an APK file?

Here are few methods you can try:

  1. Use obfuscation and tools like ProGuard.
  2. Encrypt some part of source and data.
  3. Use a proprietary inbuilt checksum in the app to detect tampering.
  4. Introduce code to avoid loading in a debugger, that is, let the app have the ability to detect the debugger and exit / kill the debugger.
  5. Separate the authentication as an online service.
  6. Use application diversity
  7. Use the finger printing technique for e.g., hardware signatures of the devices from different subsystem before authenticating the device.

JavaScript data grid for millions of rows

I know this question is a few years old, but jqgrid now supports virtual scrolling:

but with pagination disabled

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.


jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:


This will enable you to keep the information for which elements were checked as well.

How to use the gecko executable with Selenium

The solutions above work fine for local testing and firing up browsers from the java code.If you fancy firing up your selenium grid later then this parameter is a must have in order to tell the remote node where to find the geckodriver:


The node cannot find the gecko driver when specified in the Automation Java code.

So the complete command for the node whould be (assuming node and hub for test purposes live on same machine) :

java -Dwebdriver.gecko.driver="C:\geckodriver\geckodriver.exe" -jar selenium-server-standalone-2.53.0.jar -role node -hub http://localhost:4444/grid/register

And you should expect to see in the node log :

00:35:44.383 INFO - Launching a Selenium Grid node
Setting system property webdriver.gecko.driver to C:\geckodriver\geckodriver.exe

How to simplify a null-safe compareTo() implementation?

You can extract method:

public int cmp(String txt, String otherTxt)
    if ( txt == null )
        return otjerTxt == null ? 0 : 1;

    if ( otherTxt == null )
          return 1;

    return txt.compareToIgnoreCase(otherTxt);

public int compareTo(Metadata other) {
   int result = cmp( name,; 
   if ( result != 0 )  return result;
   return cmp( value, other.value); 


Java Calendar, getting current month value, clarification needed

Use Calendar.getInstance().get(Calendar.MONTH)+1 to get current month.

How to pass objects to functions in C++?

There are three methods of passing an object to a function as a parameter:

  1. Pass by reference
  2. pass by value
  3. adding constant in parameter

Go through the following example:

class Sample
    int *ptr;
    int mVar;

    Sample(int i)
        mVar = 4;
        ptr = new int(i);

        delete ptr;

    void PrintVal()
        cout << "The value of the pointer is " << *ptr << endl
             << "The value of the variable is " << mVar;

void SomeFunc(Sample x)
cout << "Say i am in someFunc " << endl;

int main()

  Sample s1= 10;
  char ch;
  cin >> ch;


Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4

Install .ipa to iPad with or without iTunes

In Xcode 5 open the organizer (Window > Organizer) and select "Devices" at the top. Your plugged in device should show up on the left hand side. Drag the IPA file over to that device.

In Xcode 6 and Xcode 7 open Devices (Window > Devices). Again your device should show up in the left hand column. Drag the IPA file to the list of apps underneath "Installed Apps".

For iOS 9 devices, refer to this post on how to get the app running after doing this.

Jupyter notebook not running code. Stuck on In [*]

I had the same problem.

In Jupyter main menu:

1) Kernel -> Shutdown 2) Kernel -> Restart

Initialise numpy array of unknown length

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []
    for x in y:
    a = np.array(a)

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{}}</option>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{}}</option>

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

    alt="pic id code"

How to change the font color in the textbox in C#?

RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.

PHP ini file_get_contents external url

The is related to the ini configuration setting allow_url_fopen.

You should be aware that enable that option may make some bugs in your code exploitable.

For instance, this failure to validate input may turn into a full-fledged remote code execution vulnerability:

copy($_GET["file"], "."); 

How can I access Oracle from Python?

Ensure these two and it should work:-

  1. Python, Oracle instantclient and cx_Oracle are 32 bit.
  2. Set the environment variables.

Fixes this issue on windows like a charm.

Multiple commands on a single line in a Windows batch file


echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.

That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping >nul: & echo !time!"

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping >nul: & echo !time!

How to force garbage collection in Java?

I would like to add some thing here. Please not that Java runs on Virtual Machine and not actual Machine. The virtual machine has its own way of communication with the machine. It may varry from system to system. Now When we call the GC we ask the Virtual Machine of Java to call the Garbage Collector.

Since the Garbage Collector is with Virtual Machine , we can not force it to do a cleanup there and then. Rather that we queue our request with the Garbage Collector. It depends on the Virtual Machine, after particular time (this may change from system to system, generally when the threshold memory allocated to the JVM is full) the actual machine will free up the space. :D

How to edit log message already committed in Subversion?

If you are using an IDE like eclipse, you can use this easy way.

Right click on the project -> Team - Show history

In that right click on the revision id for your commit and select 'Set commit properties'.

You can modify the message as you want from here.

File path issues in R using Windows ("Hex digits in character string" error)


Try this: x <- read.csv("C:/Users/surfcat/Desktop/2006_dissimilarity.csv", header=TRUE)


R is not able to understand normal windows paths correctly because the "\" has special meaning - it is used as escape character to give following characters special meaning (\n for newline, \t for tab, \r for carriage return, ..., have a look here ).

Because R does not know the sequence \U it complains. Just replace the "\" with "/" or use an additional "\" to escape the "\" from its special meaning and everything works smooth.


On windows, I think the best thing to do to improve your workflow with windows specific paths in R is to use e.g. AutoHotkey which allows for custom hotkeys:

  • define a Hotkey, e.g. Cntr-Shift-V
  • assigns it an procedure that replaces backslashes within your Clipboard with slaches ...
  • when ever you want to copy paste a path into R you can use Cntr-Shift-V instead of Cntr-V
  • Et-voila

AutoHotkey Code Snippet (link to homepage)

StringReplace, clipboard, clipboard, \, /, All 
SendInput, %clipboard% 

Find Item in ObservableCollection without using a loop

Here comes Linq:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title);

background-image: url("images/plaid.jpg") no-repeat; wont show up

Most important

Keep in mind that relative URLs are resolved from the URL of your stylesheet.

So it will work if folder images is inside the stylesheets folder.

From you description you would need to change it to either




Additional 1

Also you cannot have no selector..

CSS is applied through selectors..

Additional 2

You should use either the shorthand background to pass multiple values like this

background: url("../images/plaid.jpg") no-repeat;

or the verbose syntax of specifying each property on its own

background-image: url("../images/plaid.jpg");

Create a view with ORDER BY clause

Error is: FROM (SELECT empno,name FROM table1 where location = 'A' ORDER BY emp_no)

And solution is : FROM (SELECT empno,name FROM table1 where location = 'A') ORDER BY emp_no

Fork() function in C

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()

Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child. So if,


If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them. Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.

When we test the value of pid to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.

Read more about Fork

Selenium 2.53 not working on Firefox 47

If you're on a Mac do brew install geckodriver and off you go!

Get file name from URL

If you are using Spring, there is a helper to handle URIs. Here is the solution:

List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);

String's Maximum length in Java - calling length() method

Since arrays must be indexed with integers, the maximum length of an array is Integer.MAX_INT (231-1, or 2 147 483 647). This is assuming you have enough memory to hold an array of that size, of course.

Test method is inconclusive: Test wasn't run. Error?

I faced this problem in vs 2017 update 3 with Resharper Ultimate 2017.2

Restart vs or restart machine can't help.

I resolved the problem by clearing the Cache as follows:

    Resharper ->options-> Environment ->click the button 'Clear caches'


There is a button "error" (I find in Resharper 2018) in the upper right corner of the test window.

If you click the error button, it shows an error message that may help in resolving the problem.

To track the root of the problem, run Visual Studio in log mode. In vs 2017, Run the command:

      devenv /ReSharper.LogFile C:\temp\log\test_log.txt /ReSharper.LogLevel Verbose

Run the test.

Review the log file test_log.txt and search for 'error' in the file.

The log file is a great help to find the error that you can resolve or you can send the issue with the log file to the technical support team of Resharper.

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
     case $OPTION in
             exit 1

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
     exit 1

./ -t test -r server -p password -v

Sleeping in a batch file

I like Aacini's response. I added to it to handle the day and also enable it to handle centiseconds (%TIME% outputs H:MM:SS.CC):


::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT

::Wait for such a centisecond
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF %DAYS% GTR 0 GOTO delay_wait

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at

Git Clone: Just the files, please?

It sounds like you just want a copy of the source code. If so why not just copy the directory and exclude the .git directory from the copy?

How do you copy the contents of an array to a std::vector in C++ without looping?

avoid the memcpy, I say. No reason to mess with pointer operations unless you really have to. Also, it will only work for POD types (like int) but would fail if you're dealing with types that require construction.

No Multiline Lambda in Python: Why not?

You can simply use slash (\) if you have multiple lines for your lambda function


mx = lambda x, y: x if x > y \
     else y
print(mx(30, 20))

Output: 30

How to find index of list item in Swift?

In Swift 4, if you are traversing through your DataModel array, make sure your data model conforms to Equatable Protocol , implement the lhs=rhs method , and only then you can use ".index(of" . For example

class Photo : Equatable{
    var imageURL: URL?
    init(imageURL: URL){
        self.imageURL = imageURL

    static func == (lhs: Photo, rhs: Photo) -> Bool{
        return lhs.imageURL == rhs.imageURL

And then,

let index = aPhoto)

setting min date in jquery datepicker

Just in case if for example you need to put a min date, the last 3 months and max date next 3 months

   maxDate: '+3m',
   minDate: '-3m'

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

Can you display HTML5 <video> as a full screen background?

Use position:fixed on the video, set it to 100% width/height, and put a negative z-index on it so it appears behind everything.

If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.


<video id="video_background" src="video.mp4" autoplay>

(Add webm and ogg sources to support more browsers)


#video_background {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1000;

It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute:

BASH Syntax error near unexpected token 'done'

Had similar problems just now and these are two separate instances and solutions that worked for me:

Case 1. Basically, had a space after the last command within my newline-separated for-loop, eg. (imagining that | here represents the carat in a text editor showing where you are writing), this is what I saw when clicking around the end of the line of the last command in the loop:

for f in $pathToFiles
   $stuff |

Notice the space before before the carat (so far as I know, this is something cat has no option do display visually (one way you could test is with something like od -bc Changing the code to

for f in $pathToFiles
   $stuff| <--- notice the carat shows no ending space before the newline

fixed the problem.

Case 2. Was using a pseudo try-catch block for the for-loop (see like

for f in $pathToFiles
   { $stuff } || { echo "Failed to complete stuff"; exit 255; }
} || { echo "Failed to complete loop"; exit 255; }

and apparently bash did not like the nested {}s. Changing to

for f in $pathToFiles
} || { echo "Failed to complete loop"; exit 255; }

fixed the problem in this case. If anyone can further explain either of these cases, please let me know more about them in the comments.

Adding a line break in MySQL INSERT INTO text

If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');

I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

What's the difference between "git reset" and "git checkout"?

In their simplest form, reset resets the index without touching the working tree, while checkout changes the working tree without touching the index.

Resets the index to match HEAD, working tree left alone:

git reset

Conceptually, this checks out the index into the working tree. To get it to actually do anything you would have to use -f to force it to overwrite any local changes. This is a safety feature to make sure that the "no argument" form isn't destructive:

git checkout

Once you start adding parameters it is true that there is some overlap.

checkout is usually used with a branch, tag or commit. In this case it will reset HEAD and the index to the given commit as well as performing the checkout of the index into the working tree.

Also, if you supply --hard to reset you can ask reset to overwrite the working tree as well as resetting the index.

If you current have a branch checked out out there is a crucial different between reset and checkout when you supply an alternative branch or commit. reset will change the current branch to point at the selected commit whereas checkout will leave the current branch alone but will checkout the supplied branch or commit instead.

Other forms of reset and commit involve supplying paths.

If you supply paths to reset you cannot supply --hard and reset will only change the index version of the supplied paths to the version in the supplied commit (or HEAD if you don't specify a commit).

If you supply paths to checkout, like reset it will update the index version of the supplied paths to match the supplied commit (or HEAD) but it will always checkout the index version of the supplied paths into the working tree.

Remove characters from NSString?

if the string is mutable, then you can transform it in place using this form:

[string replaceOccurrencesOfString:@" "
                             range:NSMakeRange(0, string.length)];

this is also useful if you would like the result to be a mutable instance of an input string:

NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
                             range:NSMakeRange(0, string.length)];

Simple C example of doing an HTTP POST and consuming the response

Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:

memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
    printf("RESPONSE: %s\n", response);
    memset(response, 0, sizeof(response));
    bytes = recv(sockfd, response, 1024, 0);
    if (bytes < 0)
        printf("ERROR reading response from socket");
    if (bytes == 0)
} while (1); 

How can I check file size in Python?

import os

def convert_bytes(num):
    this function will convert bytes to MB.... GB... etc
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def file_size(file_path):
    this function will return the file size
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

# Lets check the file size of MS Paint exe 
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)


6.1 MB

Where to find the complete definition of off_t type?

If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)

Send cookies with curl

Very annoying, no cookie file exmpale on the official website

Finnaly, I find it does not work, if your file content is just copyied like this


I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.

So try this way, it works

curl -H "Cookie:`cat ./my.cookie`"

You can just copy the cookie from chrome console network tab.

Why should the static field be accessed in a static way?

There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.

Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:

public class A {
    public static String VALUE = "Aaa";

public class B extends A {
    public static String VALUE = "Bbb";

Direct access to the static variable:

A.VALUE (="Aaa")
B.VALUE (="Bbb")

Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

new B().VALUE (="Bbb")

So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

Now to the point where it gets tricky: Interfaces can also have static variables.

public interface C {
    public static String VALUE = "Ccc";

public interface D {
    public static String VALUE = "Ddd";

Let's remove the static variable from B, and observe following situations:

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C where A implements D
  • B extends A implements C where C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.

Reusing output from last command in Bash

If you don't want to recompute the previous command you can create a macro that scans the current terminal buffer, tries to guess the -supposed- output of the last command, copies it to the clipboard and finally types it to the terminal.

It can be used for simple commands that return a single line of output (tested on Ubuntu 18.04 with gnome-terminal).

Install the following tools: xdootool, xclip , ruby

In gnome-terminal go to Preferences -> Shortcuts -> Select all and set it to Ctrl+shift+a.

Create the following ruby script:

cat >${HOME}/parse.rb <<EOF
stdin =
d = stdin.split(/\n/)
e = d.reverse
f = e.drop_while { |item| item == "" }
g = f.drop_while { |item| item.start_with? "${USER}@" }
h = g[0] 
print h

In the keyboard settings add the following keyboard shortcut:

bash -c '/bin/sleep 0.3 ; xdotool key ctrl+shift+a ; xdotool key ctrl+shift+c ; ( (xclip -out | ${HOME}/parse.rb ) > /tmp/clipboard ) ; (cat /tmp/clipboard | xclip -sel clip ) ; xdotool key ctrl+shift+v '

The above shortcut:

  • copies the current terminal buffer to the clipboard
  • extracts the output of the last command (only one line)
  • types it into the current terminal

How to ignore SSL certificate errors in Apache HttpClient 4.0

Below code works with 4.5.5



import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

class HttpsSSLClient {

    public static CloseableHttpClient createSSLInsecureClient() {
        SSLContext sslcontext = createSSLContext();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() {

            public boolean verify(String paramString, SSLSession paramSSLSession) {
                return true;
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;

    private static SSLContext createSSLContext() {
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        return sslcontext;

    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};

public class TestMe {

    public static void main(String[] args) throws IOException {
        CloseableHttpClient client = HttpsSSLClient.createSSLInsecureClient();

        CloseableHttpResponse res = client.execute(new HttpGet(""));

Output from code is


Output on browser is


The pom used is below

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


    <!-- -->


How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Just select all of the files you want to compare, then open the context menu (Right-Click on the file) and choose Compare With, Then select each other..

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium: