Programs & Examples On #Mouseout

A mouseout is an event that occurs on an element when the user removes the cursor from that element

Change background color on mouseover and remove it after mouseout

If you don't care about IE =6, you could use pure CSS ...

.forum:hover { background-color: #380606; }

.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see */_x000D_
#blue { background-color: blue; }
<meta charset=utf-8>_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>

With jQuery, usually it is better to create a specific class for this style:

.forum_hover { background-color: #380606; }

and then apply the class on mouseover, and remove it on mouseout.


.forum_hover { background-color: #380606 !important; }_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
<meta charset=utf-8>_x000D_
<script src=""></script>_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>

If you must not modify the class, you could save the original background color in .data():

  $('.forum').data('bgcolor', '#380606').hover(function(){
    var $this = $(this);
    var newBgc = $'bgcolor');
    $'bgcolor', $this.css('background-color')).css('background-color', newBgc);

  $('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
    var $this = $(this);_x000D_
    var newBgc = $'bgcolor');_x000D_
    $'bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
<meta charset=utf-8>_x000D_
<script src=""></script>_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>


      var $this = $(this);
      $'bgcolor', $this.css('background-color')).css('background-color', '#380606');
      var $this = $(this);
      $this.css('background-color', $'bgcolor'));

      var $this = $(this);_x000D_
      $'bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
      var $this = $(this);_x000D_
      $this.css('background-color', $'bgcolor'));_x000D_
  );    _x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
<meta charset=utf-8>_x000D_
<script src=""></script>_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>

How to loop through array in jQuery?

Use jQuery each(). There are other ways but each is designed for this purpose.

$.each(substr, function(index, value) { 

And do not put the comma after the last number.

IntelliJ cannot find any declarations

If you see red circle on the icon of Java files, and got warning like "cannot find declaration to go to". Then you can do something below:

  1. Right click root folder of your project/module.
  2. Mark Directory As -> Excluded.

enter image description here

It works for me. in Windows 7, Intellij 2016.1.1

How to find the cumulative sum of numbers in a list?

Assignment expressions from PEP 572 (new in Python 3.8) offer yet another way to solve this:

time_interval = [4, 6, 12]

total_time = 0
cum_time = [total_time := total_time + t for t in time_interval]

Trim last character from a string

An example Extension class to simplify this: -

internal static class String
    public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
    public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
    public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;

    private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;


"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)

"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something'  (End Characters removed)

"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!'  (Only End instances removed)

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(
    at java.lang.reflect.Method.invoke(
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

Can't import javax.servlet.annotation.WebServlet

Copy servlet-api.jar from your tomcat server lib folder.

enter image description here

Paste it to WEB-INF > lib folder

enter image description here

Error was solved!!!

How to add new column to MYSQL table?


global $wpdb;

$your_table  = $wpdb->prefix. 'My_Table_Name';
$your_column =                'My_Column_Name'; 

if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
    "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"

How to position a DIV in a specific coordinates?

Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

var d = document.getElementById('yourDivId'); = "absolute"; = x_pos+'px'; = y_pos+'px';

Or do it as a function so you can attach it to an event like onmousedown

function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('yourDivId'); = "absolute"; = x_pos+'px'; = y_pos+'px';

Install tkinter for Python

I think you have to install the tkinter onto your code repository directory.

For liunx (Ubuntu or debian), open the terminal. Install the tkinter package by running this command on the terminal.

sudo apt-get install python-tk 

After installing the python-tk package on the terminal, create a new python file. Call it

On the first line of the, import tkinter into the python file.

import tkinter

To create a tkinter with different fields, you can use this tutorial.

The documentation of tkinter can be found here:

Hope that helps. Do ask us if you are still stuck. Remember to identify what you need in the GUI on tkinter before implementing it. Drawing wireframes of how the GUI will look like will help in coding the Tkinter GUI.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)


to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

How to check type of variable in Java?

The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.

Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray() will tell you.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

How can I convert an integer to a hexadecimal string in C?

This code

int a = 5;
printf("%x\n", a);



This code

int a = 5; 
printf("0x%x\n", a);



This code

int a = 89778116;
printf("%x\n", a);



If you capitalize the x in the format it capitalizes the hex value:

int a = 89778116;
printf("%X\n", a);



If you want to print pointers you use the p format specifier:

char* str = "foo";
printf("0x%p\n", str);



What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

Angular2 handling http response

in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

It's nice because it can be used with all other Observable chained methods like .retry .map etc.

import {Observable} from 'rxjs/Rx';

  .catch(err =>  { 
     notify('UI error handling');
     return Observable.throw(err); // observable needs to be returned or exception raised
  .subscribe(data => ...) // handle success

from documentation:


(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

Import JSON file in React

The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file

fetch('./data.json').then(response => {
      return response.json();
    }).then(data => {
      // Work with JSON data here
    }).catch(err => {
      // Do something for an error here
      console.log("Error Reading data " + err);

The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.

How to create a list of objects?

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):

my_types = [str, int, float, MyClass]

`getchar()` gives the same output as the input string

There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.

If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.

As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).

main() {
    int c;
    do {
        c = getchar();
        if (c == EOF && ferror()) {
        else {
    while(c != EOF);

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Right way to convert data.frame to a numeric matrix, when df also contains strings?


From ?data.matrix:


 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "" + Searchtxt;

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

Change Input to Upper Case

I think the most easiest way to do is by using Bootstrap's class ".text-uppercase"

<input type="text" class="text-uppercase" />

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

What is the id( ) function used for?

As of in python 3 id is assigned to a value not a variable. This means that if you create two functions as below, all the three id's are the same.

>>> def xyz():
...     q=123
...     print(id(q))
>>> def iop():
...     w=123
...     print(id(w))
>>> xyz()
>>> iop()
>>> id(123)

How to remove not null constraint in sql server using query

 ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL

Is there an onSelect event or equivalent for HTML <select>?

Here is the simplest way:

<select name="ab" onchange="if (this.selectedIndex) doSomething();">
    <option value="-1">--</option>
    <option value="1">option 1</option> 
    <option value="2">option 2</option>
    <option value="3">option 3</option>

Works both with mouse selection and keyboard Up/Down keys whes select is focused.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

Configuring Log4j Loggers Programmatically

It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).

If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.

public class YourLoggingWrapper {
    private static boolean loggingIsInitialized = false;

    public YourLoggingWrapper() {
        // ...blah

    public static void debug(String debugMsg) {
        log(LogLevel.Debug, debugMsg);

    // Same for all other log levels your want to handle.
    // You mentioned TRACE and ERROR.

    private static void log(LogLevel level, String logMsg) {

        org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");

        switch(level) {
        case: Debug:
            // whatever

    // log4j logging is lazily constructed; it gets initialized
    // the first time the invoking app calls a log method
    private static void initLogging() {
        loggingIsInitialized = true;

        org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");

        // Now all the same configuration code that @oers suggested applies...
        // configure the logger, configure and add its appenders, etc.

With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!

How to copy a java.util.List into another java.util.List

You should use the addAll method. It appends all of the elements in the specified collection to the end of the copy list. It will be a copy of your list.

List<String> myList = new ArrayList<>();
List<String> copyList = new ArrayList<>();

How to read/write a boolean when implementing the Parcelable interface?

Here's how I'd do it...


dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1


myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0

How to store arbitrary data for some HTML tags

Which version of HTML are you using?

In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.

<div data-internalid="1337"></div>

In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.

If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.

How do you create nested dict in Python?

This thing is empty nested list from which ne will append data to empty dict

ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'], 

this means to create four empty dict inside data_dict

data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
    upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}



The output

{'dict0': {'val': 'a', 'val1': 'a1', 'val2': 'a2', 'val3': 'a3'}, 'dict1': {'val': 'b', 'val1': 'b1', 'val2': 'b2', 'val3': 'b3'},'dict2': {'val': 'c', 'val1': 'c1', 'val2': 'c2', 'val3': 'c3'}, 'dict3': {'val': 'd', 'val1': 'd1', 'val2': 'd2', 'val3': 'd3'}}

HTML5 validation when the input type is not "submit"

Try this out:

<script type="text/javascript">
    function test
        alert("hello world");  //write your logic here like ajax

<form action="javascript:test();" >
    firstName : <input type="text" name="firstName" id="firstName" required/><br/>
    lastName : <input type="text" name="lastName" id="lastName" required/><br/>
    email : <input type="email" name="email" id="email"/><br/>
    <input type="submit" value="Get It!" name="submit" id="submit"/>

javascript: calculate x% of a number

I use two very useful JS functions:

function rangeToPercent(number, min, max){
   return ((number - min) / (max - min));


function percentToRange(percent, min, max) {
   return((max - min) * percent + min);

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How to scroll the page when a modal dialog is longer than the screen?

position:fixed implies that, well, the modal window will remain fixed relative to the viewpoint. I agree with your assessment that it's appropriate in this scenario, with that in mind why don'y you add a scrollbar to the modal window itself?

If so, correct max-height and overflow properties should do the trick.

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

How to export a table dataframe in PySpark to csv?

If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas method and then simply use to_csv:


Otherwise you can use spark-csv:

  • Spark 1.3'mycsv.csv', 'com.databricks.spark.csv')
  • Spark 1.4+


In Spark 2.0+ you can use csv data source directly:


How to add images in select list?

I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.

Worket well for me. Hope it can help someone else.

Rounded Corners Image in Flutter

Use ClipRRect with set image property of fit: BoxFit.fill

          borderRadius: new BorderRadius.circular(10.0),
          child: Image(
            fit: BoxFit.fill,
            image: AssetImage('images/image.png'),
            width: 100.0,
            height: 100.0,

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    // user clicked yes
    // user clicked no

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

If you are simply catching a generic exception, it may benefit you to cast this as a DbEntityValidationException. This type of an exception has a Validation Errors property, and continuing to expand your way into them, you will find all the problems.

For example, if you put a break point in the catch, you can throw the following into a watch:

((System.Data.Entity.Validation.DbEntityValidationException ) ex)

An example of an error is if a field does not allow nulls, and you have a null string, you'll see it say that the field is required.

Code snippet or shortcut to create a constructor in Visual Studio

Type "ctor" + TAB + TAB (hit the Tab key twice). This will create the default constructor for the class you are in:

public MyClass()


It seems that in some cases you will have to press TAB twice.

How to capture Curl output to a file?

There are several options to make curl output to a file

 # saves it to myfile.txt
curl -o myfile.txt

# The #1 will get substituted with the url, so the filename contains the url
curl -o "file_#1.txt" 

# saves to data.txt, the filename extracted from the URL
curl -O 

# saves to filename determined by the Content-Disposition header sent by the server.
curl -O -J 

How to use callback with useState hook in react

Actually, you should avoid using this when using react hooks. It causes side effects. That's why react team create react hooks.

If you remove codes that tries to bind this, you can just simply pass setName of Parent to Child and call it in handleChange. Cleaner code!

function Parent() {
  const [Name, setName] = useState("");

  return <div> {Name} :
    <Child setName={setName} ></Child>

function Child(props) {
  const [Name, setName] = useState("");

  function handleChange(ele) {

  return (<div>
    <input onChange={handleChange} value={Name}></input>

Moreover, you don't have to create two copies of Name(one in Parent and the other one in Child). Stick to "Single Source of Truth" principle, Child doesn't have to own the state Name but receive it from Parent. Cleanerer node!

function Parent() {
  const [Name, setName] = useState("");

  return <div> {Name} :
    <Child setName={setName} Name={Name}></Child>

function Child(props) {    
  function handleChange(ele) {

  return (<div>
    <input onChange={handleChange} value={props.Name}></input>

Copying formula to the next row when inserting a new row

You need to insert the new row and then copy from the source row to the newly inserted row. Excel allows you to paste special just formulas. So in Excel:

  • Insert the new row
  • Copy the source row
  • Select the newly created target row, right click and paste special
  • Paste as formulas

VBA if required with Rows("1:1") being source and Rows("2:2") being target:

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

Counting duplicates in Excel

This can be done using pivot tables. See this youtube video for a walkthrough: Quickly Count Duplicates in Excel List With Pivot Table.

To count the number of times each item is duplicated in an Excel list, you can use a pivot table, instead of manually creating a list with formulas.

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

Want to show/hide div based on dropdown box selection

You need to either put your code at the end of the page or wrap it in a document ready call, otherwise you're trying to execute code on elements that don't yet exist. Also, you can reduce your code to:

$('#purpose').on('change', function () {
    $("#business").css('display', (this.value == '1') ? 'block' : 'none');

jsFiddle example

Extract file name from path, no matter what the os/path format

In python 3

>>> from pathlib import Path    
>>> Path("/tmp/d/a.dat").name

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

How to reset the bootstrap modal when it gets closed and open it fresh again?

you can try this

$('body').on('', '.modal', function () {

It will remove all the data from the model and reset it.

ReactJS - Add custom event listener to component

If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:

Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.

class MovieItem extends React.Component {

  componentDidMount() {
    // When the component is mounted, add your DOM listener to the "nv" elem.
    // (The "nv" elem is assigned in the render function.)
    this.nv.addEventListener("nv-enter", this.handleNvEnter);

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted.
    this.nv.removeEventListener("nv-enter", this.handleNvEnter);

  // Use a class arrow function (ES7) for the handler. In ES6 you could bind()
  // a handler in the constructor.
  handleNvEnter = (event) => {
    console.log("Nv Enter:", event);

  render() {
    // Here we render a single <div> and toggle the "aria-nv-el-current" attribute
    // using the attribute spread operator. This way only a single <div>
    // is ever mounted and we don't have to worry about adding/removing
    // a DOM listener every time the current index changes. The attrs 
    // are "spread" onto the <div> in the render function: {...attrs}
    const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};

    // Finally, render the div using a "ref" callback which assigns the mounted 
    // elem to a class property "nv" used to add the DOM listener to.
    return (
      <div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">


Example on

How to import a JSON file in ECMAScript 6?

I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).

Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:

import translationsJSON from './i18n/locale-en';

The provider is not compatible with the version of Oracle client

I had the same issue with Oracle.DataAccess.dll v4.121.2.0. with 2- homes installation (32 and 64 bit versions). 32-bit version workerd, 64-bit version didn't.

In my case (after 2 days of trying) I found that the problem was permissions on the 64-bit-home version. Many Directories in that version had exclusively overridden permissions where "Authenticated Users" role did not have "Read" access, which is set by default on the parent directory. Those sub-directories included "bin", "network/admin", "nls", "oracore", "RDBMS" and possibly others. I found them by filtering out "ACCESS DENIED" result in "Process Monitor" (Procmon.exe) utility from sysinternals. Once the permissions were inherited from the parent directory to those child subdirectories everything started to work.

I didn't what to override the permissions on the whole oracle home so I did them one directory at a time, but I guess if you don't worry about security so much you can reset it on the whole corresponding oracle home directory.

What is %timeit in python?

I would just like to add another useful advantage of using %timeit to answer by mu ? that:

  • You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit to built the variable that is built in an another enviroment that timeit works.

PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.

Short rot13 function - Python

As of Python 3.1, string.translate and string.maketrans no longer exist. However, these methods can be used with bytes instead.

Thus, an up-to-date solution directly inspired from Paul Rubel's one, is:

rot13 = bytes.maketrans(
b'Hello world!'.translate(rot13)

Conversion from string to bytes and vice-versa can be done with the encode and decode built-in functions.

Create instance of generic type whose constructor requires a parameter?

As Jon pointed out this is life for constraining a non-parameterless constructor. However a different solution is to use a factory pattern. This is easily constrainable

interface IFruitFactory<T> where T : BaseFruit {
  T Create(int weight);

public void AddFruit<T>( IFruitFactory<T> factory ) where T: BaseFruit {    
  BaseFruit fruit = factory.Create(weight); /*new Apple(150);*/    

Yet another option is to use a functional approach. Pass in a factory method.

public void AddFruit<T>(Func<int,T> factoryDel) where T : BaseFruit { 
  BaseFruit fruit = factoryDel(weight); /* new Apple(150); */

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
        <name>Sample Document</name>


don't fail jenkins build if execute shell fails

On the (more general) question in title - to prevent Jenkins from failing you can prevent it from seeing exit code 1. Example for ping:

bash -c "ping -c 1; exit 0"

And now you can e.g. get output of ping:

output=`bash -c "ping -c 1; exit 0"`

Of course instead of ping ... You can use any command(s) - including git commit.

Get records of current month

Check the MySQL Datetime Functions:

Try this:

FROM tableA 
      MONTH(columnName) = MONTH(CURRENT_DATE());

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I've had the same problem before recognized that I've put the code after closing the body tag. After moving it into tag, it's OK now

        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 3

Run a script in Dockerfile

It's best practice to use COPY instead of ADD when you're copying from the local file system to the image. Also, I'd recommend creating a sub-folder to place your content into. If nothing else, it keeps things tidy. Make sure you mark the script as executable using chmod.

Here, I am creating a scripts sub-folder to place my script into and run it from:

RUN mkdir -p /scripts
COPY /scripts
WORKDIR /scripts
RUN chmod +x

How to use SQL Select statement with IF EXISTS sub query?


matplotlib error - no module named tkinter

For Linux

Debian based distros:

sudo apt-get install python3-tk

RPM based distros:

sudo yum install python3-tkinter

For windows:

For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: . Good python distributions for Windows can be found by the companies Anaconda or ActiveState.

Test the python module

python -c "import tkinter"

p.s. I suggest installing ipython, which provides powerful shell and necessary packages as well.

What is the email subject length limit?

I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.

I think that some pretty common limitations for subject lines in general (not just e-mail) are:

  • 80 Characters
  • 128 Characters
  • 256 Characters

Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.

Hope this helps!

CSS/HTML: What is the correct way to make text italic?

I'd say use <em> to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...

If you're emphasizing text for ANY reason, you could use <em>, or a class that italicizes your text.

It's OK to break the rules sometimes!

How to make a div center align in HTML

<!DOCTYPE html>_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

Validating Phone Numbers Using Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../Homepage-30-06-2016/Css.css" >

<script type="text/javascript">

        function isChar(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 47 && charCode < 58) {

                document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
                document.getElementById("fullname").style.borderColor = 'red';
                return false;
            else {
                document.getElementById("error").innerHTML = "";
                document.getElementById("fullname").style.borderColor = '';

                return true;


        <h1 style="margin-left:20px;"Registration Form>Registration Form</h1><hr/>

           Name: <input id="fullname" type="text" placeholder="Full Name*"
                 name="fullname" onKeyPress="return isChar(event)" onChange="return isChar(event);"/><label id="error"></label><br /><br />

<button type="submit" id="submit" name="submit" onClick="return valid(event)" class="btn btn-link text-uppercase"> Submit now</button>

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

// Model
public string Test { get; set; }

// View

// Output
<label for="Test">Test</label>

Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

// Model
public class MyModel
    [DisplayName("A property")]
    public string Test { get; set; }

// View
@model MyModel
@Html.LabelFor(m => m.Test)

// Output
<label for="Test">A property</label>

Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

// Model
public class MyModel
    [DisplayName("A property")]
    public string Test { get; set; }

// Main view
@Html.EditorFor(m => m.Test)

// Inside editor template

// Output
<label for="Test">A property</label>

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.


This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

String isNullOrEmpty in Java?

In addition to the other answers, I ran across this because I'm a C# programmer primarily, but trying to keep fresh in Java. I noticed that when I tried to use StringUtils my IDE (Eclipse) imported it from com.mysql.jdbc.StringUtils which actually has an isNullOrEmpty(myStringObject) method.


import com.mysql.jdbc.StringUtils;


Just another alternative for those who already have the MySQL connector referenced in your project, but not the other StringUtils library.

How can I inspect element in chrome when right click is disabled?

So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way

How to access static resources when mapping a global front controller servlet on /*

What you do is add a welcome file in your web.xml


And then add this to your servlet mappings so that when someone goes to the root of your application, they get sent to index.html internally and then the mapping will internally send them to the servlet you map it to


End result: You visit /Application, but you are presented with /Application/MainActions servlet without disrupting any other root requests.

Get it? So your app still sits at a sub url, but automatically gets presented when the user goes to the root of your site. This allows you to have the /images/bob.img still go to the regular place, but '/' is your app.

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

How to put multiple statements in one line?

You could use the built-in exec statement, eg.:

exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello',  sam) \nexcept: pass")

Where \n is a newline and \t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

Disable all dialog boxes in Excel while running VB script?

In order to get around the Enable Macro prompt I suggest

Application.AutomationSecurity = msoAutomationSecurityForceDisable

Be sure to return it to default when you are done

Application.AutomationSecurity = msoAutomationSecurityLow

A reminder that the .SaveAs function contains all optional arguments.I recommend removing CreatBackup:= False as it is not necessary.

The most interesting way I think is to create an object of the workbook and access the .SaveAs property that way. I have not tested it but you are never using Workbooks.Open rendering Application.AutomationSecurity inapplicable. Possibly saving resources and time as well.

That said I was able to execute the following without any notifications on Excel 2013 windows 10.

    Option Explicit

    Sub Convert()

    OptimizeVBA (True)  
    'function to set all the things you want to set, but hate keying in

    Application.AutomationSecurity = msoAutomationSecurityForceDisable  
    'this should stop those pesky enable prompts

    ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to 
    xlsx stop popup"

    Workbooks.Open ("Book1.xlsm")

    ActiveWorkbook.SaveAs Filename:= _
    "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_ 
    stop popup\Book1.xlsx" _
    , FileFormat:=xlOpenXMLWorkbook


    Application.AutomationSecurity = msoAutomationSecurityLow 
    'make sure you set this up when done

    Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_ 
    to xlsx stop popup\Book1.xlsx") 'clean up

    OptimizeVBA (False)
    End Sub

    Function OptimizeVBA(ByRef Status As Boolean)

    If Status = True Then
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        Application.DisplayAlerts = False
        Application.EnableEvents = False
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    End If

    End Function

concatenate two database columns into one resultset column

Just Cast Column As Varchar(Size)

If both Column are numeric then use code below.


Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

What will be the size of col3 it will be 40 or something else

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

Check to see if the user is suspended in GitHub. Access their user page and if a banner is across the top of the page that says, "This user is suspended." that is probably your issue.

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
    def __exit__(self, type, value, traceback):

Calculate distance in meters when you know longitude and latitude in java

In C++ it is done like this:

#define LOCAL_PI 3.1415926535897932385 

double ToRadians(double degrees) 
  double radians = degrees * LOCAL_PI / 180;
  return radians;

double DirectDistance(double lat1, double lng1, double lat2, double lng2) 
  double earthRadius = 3958.75;
  double dLat = ToRadians(lat2-lat1);
  double dLng = ToRadians(lng2-lng1);
  double a = sin(dLat/2) * sin(dLat/2) + 
             cos(ToRadians(lat1)) * cos(ToRadians(lat2)) * 
             sin(dLng/2) * sin(dLng/2);
  double c = 2 * atan2(sqrt(a), sqrt(1-a));
  double dist = earthRadius * c;
  double meterConversion = 1609.00;
  return dist * meterConversion;

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :


Difference between abstraction and encapsulation?

encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.

abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"

examples of encapsulation:

  • underpants
  • toolbox
  • wallet
  • handbag
  • capsule
  • frozen carbonite
  • a box, with or without a button on it
  • a burrito (technically, the tortilla around the burrito)

examples of abstraction:

  • "groups of things" is an abstraction (which we call aggregation)
  • "things that contains other things" is an abstraction (which we call composition)
  • "container" is another kind of "things that contain other things" abstraction; note that all of the encapsulation examples are kinds of containers, but not all containers exhibit/provide encapsulation. A basket, for example, is a container that does not encapsulate its contents.

Rails server says port already used, how to kill that process?

Some times there is a chance where rails server not closed properly. You can find process used by rails

ps aux | grep rails

Output will be like

user     12609  9.8  0.5  66456 45480 pts/0    Sl+  21:06   0:02 /home/user/.rvm/rubies/ruby-2.2.0-preview1/bin/ruby bin/rails s

Here process_id 12609 is used by your rails server.

You can kill it easily by command

kill -9 12609

Find files containing a given text

find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'

How to fix Cannot find module 'typescript' in Angular 4?

Run: npm link typescript if you installed globally

But if you have not installed typescript try this command: npm install typescript

"SSL certificate verify failed" using pip to install packages

It looks like they are also using now. I added the following to %appdata%\pip\pip.ini and was able to download my packages from behind an HTTPS-intercepting proxy:

trusted-host =

How do I add a delay in a JavaScript loop?

Here is how I created an infinite loop with a delay that breaks on a certain condition:

  // Now continuously check the app status until it's completed, 
  // failed or times out. The isFinished() will throw exception if
  // there is a failure.
  while (true) {
    let status = await this.api.getStatus(appId);
    if (isFinished(status)) {
    } else {
      // Delay before running the next loop iteration:
      await new Promise(resolve => setTimeout(resolve, 3000));

The key here is to create a new Promise that resolves by timeout, and to await for its resolution.

Obviously you need async/await support for that. Works in Node 8.

how to select first N rows from a table in T-SQL?


ORDERED_UNIQUE_COLUMN could be your incrementing primary key or a timestamp

How to copy data to clipboard in C#


You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

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

using recursion

let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
    if (arr.length !== 0) {
      if(i % size == 0) {
      createMatrix(arr, i - 1)
createMatrix(myArr, myArr.length);

Note: The existing array i.e. myArr will be modified.

How to get setuptools and easy_install?

For python3 on Ubuntu

 sudo apt-get install python3-setuptools

How to convert any Object to String?

I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString() function on a String Object.

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

Insert auto increment primary key to existing table

An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:


On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

What fixed this symptom for me (VS2013) is uninstalling then reinstalling the EF package with Nuget. The difference in the csproj file changed this...

<Reference Include="EntityFramework">

...into this...

<Reference Include="EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">

I don't fully understand why yet, but it worked at least.

How can a divider line be added in an Android RecyclerView?

Bhuvanesh BS solution works. Kotlin version of this:

import androidx.recyclerview.widget.RecyclerView

class DividerItemDecorator(private val mDivider: Drawable?) : RecyclerView.ItemDecoration() {

    override fun onDraw(
        canvas: Canvas,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {

        val dividerLeft = parent.paddingLeft
        val dividerRight = parent.width - parent.paddingRight
        for (i in 0 until parent.childCount - 1) {
            val child = parent.getChildAt(i)
            val dividerTop =
                child.bottom + (child.layoutParams as RecyclerView.LayoutParams).bottomMargin
            val dividerBottom = dividerTop + mDivider!!.intrinsicHeight
            mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)

How to get the background color code of an element in hex?

My beautiful non-standard solution


<div style="background-color:#f5b405"></div>


$(this).attr("style").replace("background-color:", "");



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

var.replace is not a function

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

This should work.

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

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

Renaming part of a filename

All of these answers are simple and good. However, I always like to add an interactive mode to these scripts so that I can find false positives.

if [[ -n $inInteractiveMode ]]
  echo -e -n "$oldFileName => $newFileName\nDo you want to do this change? [Y/n]: "
  read run

  [[ -z $run || "$run" == "y" || "$run" == "Y" ]] && mv "$oldFileName" "$newFileName"

Or make interactive mode the default and add a force flag (-f | --force) for automated scripts or if you're feeling daring. And this doesn't slow you down too much: the default response is "yes, I do want to rename" so you can just hit the enter key at each prompt (because of the ``-z $run\ test.

Multiline strings in VB.NET

Multi-line string literals in using the XElement class.

Imports System.Xml.Linq

Public Sub Test()

dim sOderBy as string = ""

dim xe as XElement = <SQL>
                SELECT * FROM <%= sTableName %>
                 <ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>

'** conditionally remove a section 
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove

'** convert XElement value to a string 
dim sSQL as String = xe.Value

End Sub

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

How do I concatenate strings and variables in PowerShell?

You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet:

Write-Host ($assoc.Id + "  -  "  + $assoc.Name + "  -  " + $assoc.Owner)

MySQL - ERROR 1045 - Access denied

Try connecting without any password:

mysql -u root

I believe the initial default is no password for the root account (which should obviously be changed as soon as possible).

How to display JavaScript variables in a HTML page without document.write

innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.

 document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";

Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as = "100%";

PHP If Statement with Multiple Conditions

you can use in_array function of php

$array=array('abc', 'def', 'hij', 'klm', 'nop');

if (in_array($val,$array))
  echo 'Value found';

Computed / calculated / virtual / derived columns in PostgreSQL

I have a code that works and use the term calculated, I'm not on postgresSQL pure tho we run on PADB

here is how it's used

create table some_table as
    select  category, 
            max(first_true_origin) as true_origin,
            max(first_true_dest ) as true_destination,
            max(id) as id,
            count(id) as tkts_cnt,
            (case when calculated tkts_cnt=1 then 1 else 0 end) as one_way
    from some_rando_table
    group by 1,2,3,4    ;

How can I set the opacity or transparency of a Panel in WinForms?

Try this:

panel1.BackColor = Color.FromArgb(100, 88, 44, 55);

change alpha(A) to get desired opacity.

Create an Excel file using vbscripts

Here is a sample code

strFileName = "c:\test.xls"

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Add()


Zoom in on a point (using scale and translate)

if(wheel > 0) {
    this.scale *= 1.1; 
    this.offsetX -= (mouseX - this.offsetX) * (1.1 - 1);
    this.offsetY -= (mouseY - this.offsetY) * (1.1 - 1);
else {
    this.scale *= 1/1.1; 
    this.offsetX -= (mouseX - this.offsetX) * (1/1.1 - 1);
    this.offsetY -= (mouseY - this.offsetY) * (1/1.1 - 1);

Background color for Tk in Python

I know this is kinda an old question but:

root["bg"] = "black"

will also do what you want and it involves less typing.

python tuple to dict

Even more concise if you are on python 2.7:

>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}

How to change the default docker registry from to my private registry?

Earlier this could be achieved using DOCKER_OPTS in the /etc/default/docker config file which worked on Ubuntu 14:04 and had some issues on Ubuntu 15:04. Not sure if this has been fixed.

The below line needs to go into the file /etc/default/docker on the host which runs the docker daemon. The change points to the private registry is installed in your local network. Note: you would require to restart the docker service followed with this change.

DOCKER_OPTS="--insecure-registry <priv registry hostname/ip>:<port>"

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

This error message can be thrown in the application logs when the actual issue is that the oracle database server ran out of space.

After correcting the space issue, this particular error message disappeared.

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I've run into this with a couple virtual environments.

pip uninstall MySQL-python
pip install -U MySQL-python

Worked both times.

Convert a dataframe to a vector (by rows)

You can try this to get your combination:

as.numeric(rbind(test$x, test$y))

which will return:

26, 34, 21, 29, 20, 28

Git Push ERROR: Repository not found

I had the same problem. My issue was misunderstanding that I had to first create the empty repo on github before pushing to it. Doh! Including this here for anyone else who doesn't realize.

How to get current time in python and break up into year, month, day, hour, minute?

The datetime answer by tzaman is much cleaner, but you can do it with the original python time module:

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers


[2016, 3, 11, 8, 29, 47]

Passing HTML input value as a JavaScript Function Parameter

do you use jquery? if then:


or use original javascript(DOM)




if you want to learn more, w3chool can help you a lot.

How to convert float value to integer in php?

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

execute function after complete page load

window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)

How to get last items of a list in Python?

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]

Set focus to field in dynamically loaded DIV

$("#display").load("?control=msgs", {}, function() { 

i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help

How to get my activity context?

you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()

"Large data" workflows using pandas

I think the answers above are missing a simple approach that I've found very useful.

When I have a file that is too large to load in memory, I break up the file into multiple smaller files (either by row or cols)

Example: In case of 30 days worth of trading data of ~30GB size, I break it into a file per day of ~1GB size. I subsequently process each file separately and aggregate results at the end

One of the biggest advantages is that it allows parallel processing of the files (either multiple threads or processes)

The other advantage is that file manipulation (like adding/removing dates in the example) can be accomplished by regular shell commands, which is not be possible in more advanced/complicated file formats

This approach doesn't cover all scenarios, but is very useful in a lot of them

How to view AndroidManifest.xml from APK file?

There is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer:

Also if you wish just to check on some params you can, by their UI

How to make a <div> or <a href="#"> to align center

You can put in in a paragraph

<p style="text-align:center;"><a href="contact.html" class="button large hpbottom">Get Started</a></p>

To align a div in the center, you have to do 2 things: - Make the div a fixed width - Set the left and right margin properties variable

<div class="container">
 <div style="width:100px; margin:0 auto;">
     <span>a centered div</span>

How to pass a callback as a parameter into another function

Yup. Function references are just like any other object reference, you can pass them around to your heart's content.

Here's a more concrete example:

function foo() {
    console.log("Hello from foo!");

function caller(f) {
    // Call the given function

function indirectCaller(f) {
    // Call `caller`, who will in turn call `f`

// Do it
indirectCaller(foo); // logs "Hello from foo!"

You can also pass in arguments for foo:

function foo(a, b) {
    console.log(a + " + " + b + " = " + (a + b));

function caller(f, v1, v2) {
    // Call the given function
    f(v1, v2);

function indirectCaller(f, v1, v2) {
    // Call `caller`, who will in turn call `f`
    caller(f, v1, v2);

// Do it
indirectCaller(foo, 1, 2); // logs "1 + 2 = 3"

How to construct a relative path in Java from two absolute paths (or URLs)?

Cool!! I need a bit of code like this but for comparing directory paths on Linux machines. I found that this wasn't working in situations where a parent directory was the target.

Here is a directory friendly version of the method:

 public static String getRelativePath(String targetPath, String basePath, 
     String pathSeparator) {

 boolean isDir = false;
   File f = new File(targetPath);
   isDir = f.isDirectory();
 //  We need the -1 argument to split to make sure we get a trailing 
 //  "" token if the base ends in the path separator and is therefore
 //  a directory. We require directory paths to end in the path
 //  separator -- otherwise they are indistinguishable from files.
 String[] base = basePath.split(Pattern.quote(pathSeparator), -1);
 String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);

 //  First get all the common elements. Store them as a string,
 //  and also count how many of them there are. 
 String common = "";
 int commonIndex = 0;
 for (int i = 0; i < target.length && i < base.length; i++) {
     if (target[i].equals(base[i])) {
         common += target[i] + pathSeparator;
     else break;

 if (commonIndex == 0)
     //  Whoops -- not even a single common path element. This most
     //  likely indicates differing drive letters, like C: and D:. 
     //  These paths cannot be relativized. Return the target path.
     return targetPath;
     //  This should never happen when all absolute paths
     //  begin with / as in *nix. 

 String relative = "";
 if (base.length == commonIndex) {
     //  Comment this out if you prefer that a relative path not start with ./
     relative = "." + pathSeparator;
 else {
     int numDirsUp = base.length - commonIndex - (isDir?0:1); /* only subtract 1 if it  is a file. */
     //  The number of directories we have to backtrack is the length of 
     //  the base path MINUS the number of common path elements, minus
     //  one because the last element in the path isn't a directory.
     for (int i = 1; i <= (numDirsUp); i++) {
         relative += ".." + pathSeparator;
 //if we are comparing directories then we 
 if (targetPath.length() > common.length()) {
  //it's OK, it isn't a directory
  relative += targetPath.substring(common.length());

 return relative;

add an element to int [] array in java

The ... can only be used in JDK 1.5 or later. If you are using JDK 4 or lower, use this code:'

public static int[] addElement(int[] original, int newelement) {
    int[] nEw = new int[original.length + 1];
    System.arraycopy(original, 0, nEw, 0, original.length);
    nEw[original.length] = newelement;

otherwise (JDK 5 or higher):

public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
    int[] nEw = new int[original.length + elements.length];
    System.arraycopy(original, 0, nEw, 0, original.length);
    System.arraycopy(elements, 0, nEw, original.length, elements.length);
    return nEw;

Of course, as many have mentioned above, you could use a Collection or an ArrayList, which allows you to use the .add() method.

Can I multiply strings in Java to repeat sequences?

No. Java does not have this feature. You'd have to create your String using a StringBuilder, and a loop of some sort.

Spark : how to run spark file from spark shell

Tested on both spark-shell version 1.6.3 and spark2-shell version, you can directly pipe to the shell's stdin like

spark-shell <<< "1+1"

or in your use case,

spark-shell < file.spark

Appending values to dictionary in Python

You should use append to add to the list. But also here are few code tips:

I would use dict.setdefault or defaultdict to avoid having to specify the empty list in the dictionary definition.

If you use prev to to filter out duplicated values you can simplfy the code using groupby from itertools Your code with the amendments looks as follows:

import itertools
def make_drug_dictionary(data):
    drug_dictionary = {}
    for key, row in itertools.groupby(data, lambda x: x[11]):
    return drug_dictionary

If you don't know how groupby works just check this example:

>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

How to initialize a JavaScript Date to a particular time zone

I had the same problem but we can use the time zone we want
we use .toLocaleDateString()


var day=new Date();
const options= {day:'numeric', month:'long', year:"numeric", timeZone:"Asia/Kolkata"};
const today=day.toLocaleDateString("en-IN", options);

How to restrict user to type 10 digit numbers in input element?

The snippet below does the job as expected!

<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />

//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->

How to make div background color transparent in CSS

    /*Fully Opaque*/
    .class-name {

    .class-name {

    .class-name {

    /*or you can use a transparent rgba value like this*/
      background-color: rgba(255, 242, 0, 0.7);

    /*Note - Opacity value can be anything between 0 to 1;
    Eg(0.1,0.8)etc */

jquery click event not firing?

Is this markup added to the DOM asynchronously? You will need to use live in that case:

NOTE: .live has been deprecated and removed in the latest versions of jQuery (for good reason). Please refer to the event delegation strategy below for usage and solution.

        $('.play_navigation a').live('click', function(){
            console.log("this is the click");
            return false;

The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live (or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.

Using jQuery 1.7 event delegation:

$(function () {

    $('.play_navigation').on('click', 'a', function (e) {
        console.log('this is the click');


You can also delegate events up to the document if you feel that you would like to bind the event before the document is ready (note that this also causes jQuery to examine every click event to determine if the element matches the appropriate selector):

$(document).on('click', '.play_navigation a', function (e) {
    console.log('this is the click');

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In order for System.loadLibrary() to work, the library (on Windows, a DLL) must be in a directory somewhere on your PATH or on a path listed in the java.library.path system property (so you can launch Java like java -Djava.library.path=/path/to/dir).

Additionally, for loadLibrary(), you specify the base name of the library, without the .dll at the end. So, for /path/to/something.dll, you would just use System.loadLibrary("something").

You also need to look at the exact UnsatisfiedLinkError that you are getting. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no foo in java.library.path

then it can't find the foo library (foo.dll) in your PATH or java.library.path. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError:

then something is wrong with the library itself in the sense that Java is not able to map a native Java function in your application to its actual native counterpart.

To start with, I would put some logging around your System.loadLibrary() call to see if that executes properly. If it throws an exception or is not in a code path that is actually executed, then you will always get the latter type of UnsatisfiedLinkError explained above.

As a sidenote, most people put their loadLibrary() calls into a static initializer block in the class with the native methods, to ensure that it is always executed exactly once:

class Foo {

    static {

    public Foo() {


cannot open shared object file: No such file or directory

Copied from my answer here:

Run ldconfig as root to update the cache - if that still doesn't help, you need to add the path to the file (just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directory

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

Can a PDF file's print dialog be opened with Javascript?

Why not use the Actions menu option to set this?

Do the following: If you have Acrobat Pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose 'Execute a menu item'. Click the Add button then select 'File > Print' then OK. Click OK again and save the PDF.

How to use Git and Dropbox together?

I've been using Mercurial in the recommended manner and urge that you be cautious, especially if any of the machines differ. The Dropbox fora are full of complaints of mysterious filename case problems turning up spontaneously. Hg (and I presume Git) won't notice or complain during routine checkins and you'll only hear about the corruption when it complains of a corrupt repo when you try to use it for real. Bad news. Wish I could be more specific about the problem and its workarounds; I'm still trying to dig out from this mess myself.

Oracle listener not running and won't start

Same happened to me after I changed computer name. To fix that, just locate listener.ora file and replace old computer name with the new one

What exactly is nullptr?

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

How to display UTF-8 characters in phpMyAdmin?

Here is my way how do I restore the data without looseness from latin1 to utf8:

     * Fixes the data in the database that was inserted into latin1 table using utf8 encoding.
     * DO NOT execute "SET NAMES UTF8" after mysql_connect.
     * Your encoding should be the same as when you firstly inserted the data.
     * In my case I inserted all my utf8 data into LATIN1 tables.
     * The data in tables was like ДЕТСКИÐ.
     * But my page presented the data correctly, without "SET NAMES UTF8" query.
     * But phpmyadmin did not present it correctly.
     * So this is hack how to convert your data to the correct UTF8 format.
     * Execute this code just ONCE!
     * Don't forget to make backup first!
    public function fixIncorrectUtf8DataInsertedByLatinEncoding() {
        // mysql_query("SET NAMES LATIN1") or die(mysql_error()); #uncomment this if you already set UTF8 names somewhere

        // get all tables in the database
        $tables = array();
        $query = mysql_query("SHOW TABLES");
        while ($t = mysql_fetch_row($query)) {
            $tables[] = $t[0];
        // you need to set explicit tables if not all tables in your database are latin1 charset
        // $tables = array('mytable1', 'mytable2', 'mytable3'); # uncomment this if you want to set explicit tables

        // duplicate tables, and copy all data from the original tables to the new tables with correct encoding
        // the hack is that data retrieved in correct format using latin1 names and inserted again utf8
        foreach ($tables as $table)  {
            $temptable = $table . '_temp';
            mysql_query("CREATE TABLE $temptable LIKE $table") or die(mysql_error());
            mysql_query("ALTER TABLE $temptable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci") or die(mysql_error());
            $query = mysql_query("SELECT * FROM `$table`") or die(mysql_error());
            mysql_query("SET NAMES UTF8") or die(mysql_error());
            while ($row = mysql_fetch_row($query)) {
                $values = implode("', '", $row);
                mysql_query("INSERT INTO `$temptable` VALUES('$values')") or die(mysql_error());
            mysql_query("SET NAMES LATIN1") or die(mysql_error());

        // drop old tables and rename temporary tables
        // this actually should work, but it not, then
        // comment out this lines if this would not work for you and try to rename tables manually with phpmyadmin
        foreach ($tables as $table)  {
            $temptable = $table . '_temp';
            mysql_query("DROP TABLE `$table`") or die(mysql_error());
            mysql_query("ALTER TABLE `$temptable` RENAME `$table`") or die(mysql_error());
        // now you data should be correct

        // change the database character set
        mysql_query("ALTER DATABASE DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci") or die(mysql_error());

        // now you can use "SET NAMES UTF8" in your project and mysql will use corrected data

How to copy directories with spaces in the name

You should write brackets only before path: "c:\program files\

Algorithm to randomly generate an aesthetically-pleasing color palette

JavaScript adaptation of David Crow's original answer, IE and Nodejs specific code included.

generateRandomComplementaryColor = function(r, g, b){
    //--- JavaScript code
    var red = Math.floor((Math.random() * 256));
    var green = Math.floor((Math.random() * 256));
    var blue = Math.floor((Math.random() * 256));

    //--- Extra check for Internet Explorers, its Math.random is not random enough.
    if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){
        red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
        green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
        blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));

    //--- nodejs code
    crypto = Npm.require('crypto');
    red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
    green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
    blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);

    red = (red + r)/2;
    green = (green + g)/2;
    blue = (blue + b)/2;

    return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';

Run the function using:

generateRandomComplementaryColor(240, 240, 240);

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

I am using jquery or vw to keep the ratio


function setSize() {
    var $h = $('.cell').width();
$( window ).resize(setSize); 


.cell img{

Dependency Injection vs Factory Pattern

IOC is a concept which is implemented by two ways. Dependency creation and dependency injection, Factory/Abstract factory are the example of dependency creation. Dependency injection is constructor, setter and interface. The core of IOC is to not depend upon the concrete classes, but define the abstract of methods(say an Interface/abstract class) and use that abstract to call method of concrete class. Like Factory pattern return the base class or interface. Similariliy dependency injection use base class/interface to set value for objects.

Twitter Bootstrap - full width navbar

You need to push the container down the navbar.

Please find my working fiddle here


    <h2 class="title">Test</h2>
<div class="navbar">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>

<div class="container">


java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

git branch --set-upstream-to=origin/master 

Or, if master isn't the currently checked-out branch:

git branch --set-upstream-to=origin/master master

How to convert ASCII code (0-255) to its corresponding character?

upper answer only near solving the Problem. heres your answer:

Integer.decode(Character.toString(char c));

How to put a jpg or png image into a button in HTML

<a href="#">
        <img src="p.png"></img>

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]

How do you change the colour of each category within a highcharts column chart?

You can also set the color individually for each point/bar if you change the data array to be configuration objects instead of numbers.

data: [
      {y: 34.4, color: 'red'},     // this point is red
      21.8,                        // default blue
      {y: 20.1, color: '#aaff99'}, // this will be greenish
      20]                          // default blue

Example on jsfiddle

enter image description here

Git Symlinks in Windows

One simple trick we use is to just call git add --all twice in a row.

For example, our Windows 7 commit script calls:

$ git add --all
$ git add --all

The first add treats the link as text and adds the folders for delete.

The second add traverses the link correctly and undoes the delete by restoring the files.

It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.

Convert array of strings into a string in Java

Try the Arrays.toString overloaded methods.

Or else, try this below generic implementation:

public static void main(String... args) throws Exception {

    String[] array = {"ABC", "XYZ", "PQR"};

    System.out.println(new Test().join(array, ", "));

public <T> String join(T[] array, String cement) {
    StringBuilder builder = new StringBuilder();

    if(array == null || array.length == 0) {
        return null;

    for (T t : array) {

    builder.delete(builder.length() - cement.length(), builder.length());

    return builder.toString();

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

in Notepad++ , you can select a particular column holding ctrl + alt + shift and then left click mouse button and drag to select.

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

i just change gradle version classpath '' to classpath '' and now working.

How to define a two-dimensional array?

Using NumPy you can initialize empty matrix like this:

import numpy as np
mm = np.matrix([])

And later append data like this:

mm = np.append(mm, [[1,2]], axis=1)

How to block users from closing a window in Javascript?

Well you can use the window.onclose event and return false in the event handler.

function closedWin() {
    confirm("close ?");
    return false; /* which will not allow to close the window */
if(window.addEventListener) {
     window.addEventListener("close", closedWin, false);

window.onclose = closedWin;

Code was taken from this site.

In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example: (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How to read attribute value from XmlNode in C#?



to get the value.

What is best tool to compare two SQL Server databases (schema and data)?

I've used SQL Delta before (, it's really good. Not free however, not sure how prices compare to Red-Gates

CSS opacity only to background color, not the text on it?


background:url("location of image"); // Use an image with opacity

This method will work in all browsers.

How to check if an array element exists?

You can also use array_keys for number of occurrences

$i=count(array_keys($array, 6));
 echo "Element exists in Array";

Found a swap file by the name

More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.

Check and kill process vm

Is it possible to capture the stdout from the sh DSL command in the pipeline

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                    steps {                                 
                            println my_var

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
    <!-- form content with input elements -->

Route [login] not defined

**Adding this for the future me.**
I encountered this because I was reusing Laravel's "HomeController", and adding my custom functions to it. Note that this controller calls the auth middleware in its __construct() method as shown below, which means that all functions must be authenticated. No wonder it tries to take you to login page first. So, if you are not using Laravel's authentication scafffolding, you will be in a mess. Disable the constructor, or do as you seem fit, now that you know what is happening.

public function __construct()

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

Convert a python dict to a string and back

I use json:

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

What's the fastest way to delete a large folder in Windows?

use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.

Also, explorer will stop if there is a particular problem with a file,

Override devise registrations controller

In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

Otherwise, I think you can just create your own controller, by generating something like this:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new

  def create
    # add custom create logic here

  def update

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

android activity has leaked window$decorview Issue

Please try this Way And Let me know :

Context mContext;
public void onCreate(Bundle savedInstanceState) {

   Button reload=(Button)findViewById(;
   showInfoMessageDialog("Please check your network connection","Network Alert"); 
public void showInfoMessageDialog(String message,String title)
   new AlertDialog.Builder(mContext)
   .setTitle("Network Alert");
   .setButton("OK",new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog,int which) 

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)

How to use radio on change event?

Simple ES6 (javascript only) solution.

document.forms.demo.bedStatus.forEach(radio => {_x000D_
  radio.addEventListener('change', () => {_x000D_
    alert(`${document.forms.demo.bedStatus.value} Thai Gayo`);_x000D_
<form name="demo">_x000D_
  <input type="radio" name="bedStatus" value="Allot" checked>Allot_x000D_
  <input type="radio" name="bedStatus" value="Transfer">Transfer_x000D_

How can I mock the JavaScript window object using Jest?

In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:

// setupTests.js
window.crypto = {

Reference: setupFilesAfterEnv [array]

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?


It does display warnings, but continues with the build

How to kill MySQL connections

No, there is no built-in MySQL command for that. There are various tools and scripts that support it, you can kill some connections manually or restart the server (but that will be slower).

Use SHOW PROCESSLIST to view all connections, and KILL the process ID's you want to kill.

You could edit the timeout setting to have the MySQL daemon kill the inactive processes itself, or raise the connection count. You can even limit the amount of connections per username, so that if the process keeps misbehaving, the only affected process is the process itself and no other clients on your database get locked out.

If you can't connect yourself anymore to the server, you should know that MySQL always reserves 1 extra connection for a user with the SUPER privilege. Unless your offending process is for some reason using a username with that privilege...

Then after you can access your database again, you should fix the process (website) that's spawning that many connections.

How to import a .cer certificate into a java keystore?

An open source GUI tool is available at

KeyStore Explorer

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

Following screens will help (they are from the official site)

Default screen that you get by running the command:


enter image description here

And go to Examine and Examine a URL option and then give the web URL that you want to import.

The result window will be like below if you give google site link. enter image description here

This is one of Use case and rest is up-to the user(all credits go to the

Typescript Type 'string' is not assignable to type

I was facing the same issue, I made below changes and the issue got resolved.

Open watchQueryOptions.d.ts file


Change the query type any instead of DocumentNode, Same for mutation


export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **DocumentNode**;


export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **any**;

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

How to properly upgrade node using nvm

Here are the steps that worked for me for Ubuntu OS and using nvm

Go to nodejs website and get the last LTS version (for example in your current dater the version will be: x.y.z)

nvm install x.y.z
# In my case current version is: 14.15.4 (and had 14.15.3)

After that, execute nvm list and you will get list of node versions installed by nvm.

Now you need to switch to the default last installed one by executing:

nvm alias default x.y.z

List again or run nvm --version to check: enter image description here

Update: sometimes even if i go over the steps above it doesn't work, so what i did was removing the symbolic links in /usr/local/bin

cd /usr/local/bin
sudo rm node npm npx

And relink:

sudo ln -s $(which node) /usr/local/bin/node
sudo ln -s $(which npm) /usr/local/bin/npm
sudo ln -s $(which npx) /usr/local/bin/npx

Git Clone from GitHub over https with two-factor authentication

Find out how to fix this here:

How does it work for command-line Git?

If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.

Angular directives - when and how to use compile, controller, pre-link and post-link

How to declare the various functions?

Compile, Controller, Pre-link & Post-link

If one is to use all four function, the directive will follow this form:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.
            return {
                pre: function preLink( scope, element, attributes, controller, transcludeFn ) {
                    // Pre-link code goes here
                post: function postLink( scope, element, attributes, controller, transcludeFn ) {
                    // Post-link code goes here

Notice that compile returns an object containing both the pre-link and post-link functions; in Angular lingo we say the compile function returns a template function.

Compile, Controller & Post-link

If pre-link isn't necessary, the compile function can simply return the post-link function instead of a definition object, like so:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.
            return function postLink( scope, element, attributes, controller, transcludeFn ) {
                    // Post-link code goes here                 

Sometimes, one wishes to add a compile method, after the (post) link method was defined. For this, one can use:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.

        link: function( scope, element, attributes, controller, transcludeFn ) {
            // Post-link code goes here


Controller & Post-link

If no compile function is needed, one can skip its declaration altogether and provide the post-link function under the link property of the directive's configuration object:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        link: function postLink( scope, element, attributes, controller, transcludeFn ) {
                // Post-link code goes here                 

No controller

In any of the examples above, one can simply remove the controller function if not needed. So for instance, if only post-link function is needed, one can use:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        link: function postLink( scope, element, attributes, controller, transcludeFn ) {
                // Post-link code goes here