Programs & Examples On #Uipopovercontroller

The UIPopoverController class is used to manage the presentation of content in a popover. You use popovers to present information temporarily. The popover content is layered on top of your existing content and the background is dimmed automatically. The popover remains visible until the user taps outside of the popover window or you explicitly dismiss it. Popover controllers are for use exclusively on iPad devices.

How to present popover properly in iOS 8

Okay, A housemate took a look at it and figured it out:

 func addCategory() {

    var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
    var nav = UINavigationController(rootViewController: popoverContent)
    nav.modalPresentationStyle = UIModalPresentationStyle.Popover
    var popover = nav.popoverPresentationController
    popoverContent.preferredContentSize = CGSizeMake(500,600)
    popover.delegate = self
    popover.sourceView = self.view
    popover.sourceRect = CGRectMake(100,100,0,0)

    self.presentViewController(nav, animated: true, completion: nil)


That's the way.

You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize

Preventing multiple clicks on button

One way you do this is set a counter and if number exceeds the certain number return false. easy as this.

var mybutton_counter=0;
$("#mybutton").on('click', function(e){
    if (mybutton_counter>0){return false;} //you can set the number to any
    //your call
     mybutton_counter++; //incremental

make sure, if statement is on top of your call.

Adding values to an array in java

I suggest you step through the code in your debugger as debugging programs is what it is for.

What I would expect you would see is that every time the code loops int x = 0; is set.

Python how to plot graph sine wave

import math
import turtle

ws = turtle.Screen()
fred = turtle.Turtle()
for angle in range(360):
    y = math.sin(math.radians(angle))
    fred.goto(angle, y * 80)


Dynamic creation of table with DOM

It is because you're only creating two td elements and 2 text nodes.

Creating all nodes in a loop

Recreate the nodes inside your loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table');

for (var i = 1; i < 4; i++) {
    var tr = document.createElement('tr');

    tr.appendChild( document.createElement('td') );
    tr.appendChild( document.createElement('td') );

    tr.cells[0].appendChild( document.createTextNode('Text1') )
    tr.cells[1].appendChild( document.createTextNode('Text2') );



Creating then cloning in a loop

Create them beforehand, and clone them inside the loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table'),
    tr = document.createElement('tr');

tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );

tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );

for (var i = 1; i < 4; i++) {
    table.appendChild(tr.cloneNode( true ));


Table factory with text string

Make a table factory:

function populateTable(table, rows, cells, content) {
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
    return table;

And use it like this:

        .appendChild( populateTable(null, 3, 2, "Text") );

Table factory with text string or callback

The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.

function populateTable(table, rows, cells, content) {
    var is_func = (typeof content === 'function');
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            var text = !is_func ? (content + '') : content(table, i, j);
    return table;

Used like this:

        .appendChild(populateTable(null, 3, 2, function(t, r, c) {
                        return ' row: ' + r + ', cell: ' + c;

Join String list elements with a delimiter in one step

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative -

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

or else simple and same as common execution


SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])

I hopes its help to you

Switch statement fallthrough in C#?

You forgot to add the "break;" statement into case 3. In case 2 you wrote it into the if block. Therefore try this:

case 3:            
    ans += string.Format("{0} hundred and ", numbers[number / 100]);

case 2:            
    int t = (number / 10) % 10;            
    if (t == 1)            
        ans += teens[number % 10];                
    else if (t > 1)                
        ans += string.Format("{0}-", tens[t]);        

case 1:            
    int o = number % 10;            
    ans += numbers[o];            

    throw new ArgumentException("number");

Convert Unix timestamp to a date string

With GNU's date you can do:

date -d "@$TIMESTAMP"
# date -d @0
Wed Dec 31 19:00:00 EST 1969

(From: BASH: Convert Unix Timestamp to a Date)

On OS X, use date -r.

date -r "$TIMESTAMP"

Alternatively, use strftime(). It's not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.

echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
# echo 0 | gawk '{print strftime("%c", $0)}'
Wed 31 Dec 1969 07:00:00 PM EST

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:


Image inside div has extra space below the image

You can use several methods for this issue like

  1. Using line-height

    #wrapper {  line-height: 0px;  }
  2. Using display: flex

    #wrapper {  display: flex;         }
    #wrapper {  display: inline-flex;  }
  3. Using display: block, table, flex and inherit

    #wrapper img {  display: block;    }
    #wrapper img {  display: table;    }
    #wrapper img {  display: flex;     }
    #wrapper img {  display: inherit;  }

Altering user-defined table types in SQL Server

Just had to do this alter user defined table type in one of my projects. Here are the steps I employed:

  1. Find all the SP using the user defined table type.
  2. Save a create script for all the SP(s) found.
  3. Drop the SP(s).
  4. Save a create script for the user defined table you wish to alter. 4.5 Add the additional column or changes you need to the user defined table type.
  5. Drop the user defined table type.
  6. Run the create script for the user defined table type.
  7. Run the create script for the SP(s).
  8. Then start modifying the SP(s) accordingly.

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );


I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

System.IO.IOException: file used by another process

It worked for me.

Here is my test code. Test run follows:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            FileInfo f = new FileInfo(args[0]);
            bool result = modifyFile(f, args[1],args[2]);
        private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) 
            Boolean result = false; 
            FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); 
            StreamWriter sw = new StreamWriter(fs); 
            StreamReader streamreader = file.OpenText(); 
            String originalPath = file.FullName; 
            string input = streamreader.ReadToEnd(); 
            Console.WriteLine("input : {0}", input); 
            String tempString = input.Replace(extractedMethod, modifiedMethod); 
            Console.WriteLine("replaced String {0}", tempString); 
                File.Copy(originalPath, originalPath + ".old", true); 
                FileInfo newFile = new FileInfo(originalPath + ".tmp"); 
                File.Copy(originalPath + ".tmp", originalPath, true); 
                result = true; 
            catch (Exception ex) 
            return result; 

C:\testarea>ConsoleApplication1.exe file.txt padding testing
input :         <style type="text/css">
         #mytable {
          border-collapse: collapse;
          width: 300px;
         #mytable th,
         #mytable td
          border: 1px solid #000;
          padding: 3px;
         #mytable tr.highlight {
          background-color: #eee;
replaced String         <style type="text/css">
         #mytable {
          border-collapse: collapse;
          width: 300px;
         #mytable th,
         #mytable td
          border: 1px solid #000;
          testing: 3px;
         #mytable tr.highlight {
          background-color: #eee;

jQuery ui dialog change title after load-callback

Even better!

    jQuery( "#dialog" ).attr('title', 'Error');
    jQuery( "#dialog" ).text('You forgot to enter your first name');

Checking if a textbox is empty in Javascript

onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

function checkTextField(field) {_x000D_
  document.getElementById("error").innerText =_x000D_
    (field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>

(Or old live demo.)

Serializing class instance to JSON

Here are two simple functions for serialization of any non-sophisticated classes, nothing fancy as explained before.

I use this for configuration type stuff because I can add new members to the classes with no code adjustments.

import json

class SimpleClass:
    def __init__(self, a=None, b=None, c=None):
        self.a = a
        self.b = b
        self.c = c

def serialize_json(instance=None, path=None):
    dt = {}

    with open(path, "w") as file:
        json.dump(dt, file)

def deserialize_json(cls=None, path=None):
    def read_json(_path):
        with open(_path, "r") as file:
            return json.load(file)

    data = read_json(path)

    instance = object.__new__(cls)

    for key, value in data.items():
        setattr(instance, key, value)

    return instance

# Usage: Create class and serialize under Windows file system.
write_settings = SimpleClass(a=1, b=2, c=3)
serialize_json(write_settings, r"c:\temp\test.json")

# Read back and rehydrate.
read_settings = deserialize_json(SimpleClass, r"c:\temp\test.json")

# results are the same.

# output:
# {'c': 3, 'b': 2, 'a': 1}
# {'c': 3, 'b': 2, 'a': 1}

Merge, update, and pull Git branches without using checkouts

You can only do this if the merge is a fast-forward. If it's not, then git needs to have the files checked out so it can merge them!

To do it for a fast-forward only:

git fetch <branch that would be pulled for branchB>
git update-ref -m "merge <commit>: Fast forward" refs/heads/<branch> <commit>

where <commit> is the fetched commit, the one you want to fast-forward to. This is basically like using git branch -f to move the branch, except it also records it in the reflog as if you actually did the merge.

Please, please, please don't do this for something that's not a fast-forward, or you'll just be resetting your branch to the other commit. (To check, see if git merge-base <branch> <commit> gives the branch's SHA1.)

How to tell if JRE or JDK is installed

the computer in question is a Mac.

A macOS-only solution:

/usr/libexec/java_home -v 1.8+ --exec javac -version

Where 1.8+ is Java 1.8 or higher.

Unfortunately, the java_home helper does not set the proper return code, so checking for failure requires parsing the output (e.g. 2>&1 |grep -v "Unable") which varies based on locale.

Note, Java may also exist in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin, but at time of writing this, I'm unaware of a JRE that installs there which contains javac as well.

How many files can I put in a directory?

I have a directory with 88,914 files in it. Like yourself this is used for storing thumbnails and on a Linux server.

Listed files via FTP or a php function is slow yes, but there is also a performance hit on displaying the file. e.g. has a wait time of 200-400 ms. As a comparison on another site I have with a around 100 files in a directory the image is displayed after just ~40ms of waiting.

I've given this answer as most people have just written how directory search functions will perform, which you won't be using on a thumb folder - just statically displaying files, but will be interested in performance of how the files can actually be used.

How do I change the default library path for R packages

Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.

The solution is editing the Rprofile file to overwrite the variable R_LIBS_USER which by default points to the home directory.

Here the steps:

  1. Create the target destination folder for the libraries, e.g., ~\target.
  2. Find the Rprofile file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile.
  3. Edit the file and change the definition the variable R_LIBS_USER. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R", with file.path("~\target", "R",.

The documentation that support this solution is here

Original file with:

                file.path(Sys.getenv("R_USER"), "R",
                                sub("\\..*$", "", R.version$minor),

Modified file:

                file.path("~\target", "R",
                                sub("\\..*$", "", R.version$minor),

ClientAbortException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

How do I POST a x-www-form-urlencoded request using Fetch?

In the original example you have a transformRequest function which converts an object to Form Encoded data.

In the revised example you have replaced that with JSON.stringify which converts an object to JSON.

In both cases you have 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' so you are claiming to be sending Form Encoded data in both cases.

Use your Form Encoding function instead of JSON.stringify.

Re update:

In your first fetch example, you set the body to be the JSON value.

Now you have created a Form Encoded version, but instead of setting the body to be that value, you have created a new object and set the Form Encoded data as a property of that object.

Don't create that extra object. Just assign your value to body.

How to limit text width

You can use word-wrap : break-word;

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file)

Using relative URL in CSS file, what location is it relative to?

One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.

The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".

In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.


JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information:

How to sum digits of an integer in java?

Java 8 Solution:

int n= 29;    

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.


sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean


sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

How to define custom configuration variables in rails

Something we've starting doing at work is the ActiveSupport Ordered Hash

Which allows you to define your configuration cleanly inside the environment files e.g.

config.service =
config.service.api_key = ENV['SERVICE_API_KEY']
config.service.shared_secret = ENV['SERVICE_SHARED_SECRET']

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

try this it will work

sudo chmod 755 /opt/lampp/phpmyadmin/


Laravel Carbon subtract days from current date

From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))

You also have whereMonth / whereDay / whereYear / whereTime

Passing Parameters JavaFX FXML

javafx.scene.Node class has a pair of methods setUserData(Object) and Object getUserData()

Which you could use to add your info to the Node.

So, you can call page.setUserData(info);

And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.

Observe a documentation here: Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."

So, you need to associate a controller with a node, and set a user data to the node.

Set UIButton title UILabel font size programmatically

Check on custom font name whether checkbox on "Target membership" is added. This should help.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

If you can update your connector to a version, which supports the new authentication plugin of MySQL 8, then do that. If that is not an option for some reason, change the default authentication method of your database user to native.

How to add two strings as if they were numbers?

Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.

    Enter the first number: <input type="text" id="num1" /><br />
    Enter the seccond number: <input type="text" id="num2" /><br />
    <input type="button" onclick="call()" value="Add"/>

    <script type="text/javascript">
    function call(){
    var q=parseInt(document.getElementById("num1").value);
    var w=parseInt(document.getElementById("num2").value);
    var result=q+w;

for more details please visit

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Twitter Bootstrap alert message close and open again

Based on the other answers and changing data-dismiss to data-hide, this example handles opening the alert from a link and allows the alert to be opened and closed repeatedly

$('a.show_alert').click(function() {
    var $theAlert = $('.my_alert'); /* class on the alert */
   // set up the close event when the alert opens
   $theAlert.find('a[data-hide]').click(function() {
     $(this).parent().hide(); /* hide the alert */

Force IE10 to run in IE10 Compatibility View?

You can try :

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

Just like you tried before, but caution:

It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

How can we dynamically allocate and grow an array

You can do something like this:

String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null)   {
     // Store the content into an array
     Scanner s = new Scanner(strLine);
     while(s.hasNext()) {
         if (wordList.length == wordCount) {
              // expand list
              wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
         wordList[wordCount] =;

Using java.util.Arrays.copyOf(String[]) is basically doing the same thing as:

if (wordList.length == wordCount) {
    String[] temp = new String[wordList.length + arrayGrowth];
    System.arraycopy(wordList, 0, temp, 0, wordList.length);
    wordList = temp;

except it is one line of code instead of three. :)

How to set the DefaultRoute to another Route in React Router

You use it like this to redirect on a particular URL and render component after redirecting from old-router to new-router.

<Route path="/old-router">
  <Redirect exact to="/new-router"/>
  <Route path="/new-router" component={NewRouterType}/>

How to clamp an integer to some range?

If your code seems too unwieldy, a function might help:

def clamp(minvalue, value, maxvalue):
    return max(minvalue, min(value, maxvalue))

new_index = clamp(0, new_index, len(mylist)-1)

How to remove title bar from the android activity?

In your Android Manifest file make sure that the activity is using this (or a) theme (that is based on) @style/Theme.AppCompat.NoActionBar This removes the ActionBar completely, but won't make your activity fullscreen. If you want to make your activity fullscreen only use this theme


Or you could change




This is what I use to get fullscreen at runtime

                mDecorView = getWindow().getDecorView();
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);

To exit fullscreen I use this

mDecorView = getWindow().getDecorView();
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

Swift error : signal SIGABRT how to solve it

To solve the problem, first clean the project and then rebuild.

To clean the project, go to MenuBar: Product -> Clean

Then to rebuild the project, just click the Run button as usual.

What is token-based authentication?

Token Based (Security / Authentication)

means that In order for us to prove that we’ve access we first have to receive the token. In a real life scenario, the token could be an access card to building, it could be the key to the lock to your house. In order for you to retrieve a key card for your office or the key to your home, you first need to prove who you are, and that you in fact do have access to that token. It could be something as simple as showing someone your ID or giving them a secret password. So imagine I need to get access to my office. I go down to the security office, I show them my ID, and they give me this token, which lets me into the building. Now I have unrestricted access to do whatever I want inside the building, as long as I have my token with me.

What’s the benefit of token based security?

If we think back on the insecure API, what we had to do in that case was that we had to provide our password for everything that we wanted to do.

Imagine that every time we enter a door in our office, we have to give everyone sitting next to the door our password. Now that would be pretty bad, because that means that anyone inside our office could take our password and impersonate us, and that’s pretty bad. Instead, what we do is that we retrieve the token, of course together with password, but we retrieve that from one person. And then we can use this token wherever we want inside the building. Of course if we lose the token, we have the same problem as if someone else knew our password, but that leads us into things like how do we make sure that if we lose the token, we can revoke the access, and maybe the token shouldn’t live for longer than 24hours, so the next day that we come to the office, we need to show our ID again. But still, there’s just one person that we show the ID to, and that’s the security guard sitting where we retrieve the tokens.

Maintaining href "open in new tab" with an onClick handler in React

React + TypeScript inline util method:

const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ?, "_blank") : window.location.href = url;

Why use deflate instead of gzip for text files served by Apache?

Why use deflate instead of gzip for text files served by Apache?

The simple answer is don't.

RFC 2616 defines deflate as:

deflate The "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951

The zlib format is defined in RFC 1950 as :

     0   1
     |CMF|FLG|   (more-->)

       0   1   2   3
     |     DICTID    |   (more-->)

     |...compressed data...|    ADLER32    |

So, a few headers and an ADLER32 checksum

RFC 2616 defines gzip as:

gzip An encoding format produced by the file compression program "gzip" (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC.

RFC 1952 defines the compressed data as:

The format presently uses the DEFLATE method of compression but can be easily extended to use other compression methods.

CRC-32 is slower than ADLER32

Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter).

So ... we have 2 compression mechanisms that use the same algorithm for compression, but a different algorithm for headers and checksum.

Now, the underlying TCP packets are already pretty reliable, so the issue here is not Adler 32 vs CRC-32 that GZIP uses.

Turns out many browsers over the years implemented an incorrect deflate algorithm. Instead of expecting the zlib header in RFC 1950 they simply expected the compressed payload. Similarly various web servers made the same mistake.

So, over the years browsers started implementing a fuzzy logic deflate implementation, they try for zlib header and adler checksum, if that fails they try for payload.

The result of having complex logic like that is that it is often broken. Verve Studio have a user contributed test section that show how bad the situation is.

For example: deflate works in Safari 4.0 but is broken in Safari 5.1, it also always has issues on IE.

So, best thing to do is avoid deflate altogether, the minor speed boost (due to adler 32) is not worth the risk of broken payloads.

Format Date output in JSF

With EL 2 (Expression Language 2) you can use this type of construct for your question:


Or you can add an alternate getter in your bean resulting in


where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.

show distinct column values in pyspark dataframe: python

Let's assume we're working with the following representation of data (two columns, k and v, where k contains three entries, two unique:

|  k|  v|
|foo|  1|
|bar|  2|
|foo|  3|

With a Pandas dataframe:

import pandas as pd
p_df = pd.DataFrame([("foo", 1), ("bar", 2), ("foo", 3)], columns=("k", "v"))

This returns an ndarray, i.e. array(['foo', 'bar'], dtype=object)

You asked for a "pyspark dataframe alternative for pandas df['col'].unique()". Now, given the following Spark dataframe:

s_df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("foo", 3)], ('k', 'v'))

If you want the same result from Spark, i.e. an ndarray, use toPandas():


Alternatively, if you don't need an ndarray specifically and just want a list of the unique values of column k:'k').distinct() r: r[0]).collect()

Finally, you can also use a list comprehension as follows:

[i.k for i in'k').distinct().collect()]

Questions every good Database/SQL developer should be able to answer

I would give a badly written query and ask them how they would go about performance tuning it.

I would ask about set theory. If you don't understand operating in sets, you can't effectively query a relational database.

I would give them some cursor examples and ask how they would rewrite them to make them set-based.

If the job involved imports and exports I would ask questions about SSIS (or other tools involved in doing this used by other datbases). If it involved writing reports, I would want to know that they understand aggregates and grouping (As well as Crystal Reports or SSRS or whatever ereporting tool you use).

I would ask the difference in results between these three queries:

select  a.field1
        , a.field2
        , b.field3
from table1 a
join table2 b
    on =
where a.field5 = 'test'
    and b.field3 = 1

select  a.field1
        , a.field2
        , b.field3
from table1 a
left join table2 b
    on =
where a.field5 = 'test'
    and b.field3 = 1

select  a.field1
        , a.field2
        , b.field3
from table1 a
left join table2 b
    on = and b.field3 = 1
where a.field5 = 'test'

Select single item from a list

Use the FirstOrDefault selector.

var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var firstEven = list.FirstOrDefault(n => n % 2 == 0);

if (firstEven == 0)
    Console.WriteLine("no even number");
    Console.WriteLine("first even number is {0}", firstEven);

Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.

If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.

Hope this helps :-)

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

(Get-Date (Get-Date -Format d)).AddHours(-2)

How to deal with SQL column names that look like SQL keywords?

Hi I work on Teradata systems that is completely ANSI compliant. Use double quotes " " to name such columns.

E.g. type is a SQL reserved keyword, and when used within quotes, type is treated as a user specified name.

See below code example:

type_of_product AS "type"
FROM beta1
PRIMARY INDEX (product1)

--type is a SQL reserved keyword


--see? now to retrieve the column you would use:

SEL "type" FROM alpha1

Extracting jar to specified directory

It's better to do this.

Navigate to the folder structure you require

Use the command

jar -xvf  'Path_to_ur_Jar_file'

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

How to Resize image in Swift?

UIImage Extension Swift 5

extension UIImage {
    func resize(_ width: CGFloat, _ height:CGFloat) -> UIImage? {
        let widthRatio  = width / size.width
        let heightRatio = height / size.height
        let ratio = widthRatio > heightRatio ? heightRatio : widthRatio
        let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        return newImage

Use : UIImage().resize(200, 300)

Is it possible to play music during calls so that the partner can hear it ? Android

I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "

What is the simplest way to SSH using Python?

I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.

import socket
import libssh2

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 22))

session = libssh2.Session()
session.userauth_password('john', '******')

channel =
channel.execute('ls -l')


What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;


// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;


// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

Why does z-index not work?

Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.

Here's an example:

<section class="content">            
    <div class="modal"></div>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;

.modal {
    position: fixed;
    z-index: 100;

.side-tab {
    position: fixed;
    z-index: 5;

In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.

Here's an article that explains 4 reasons why z-index might not work:

How to get instance variables in Python?


>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

In otherwords, it essentially just wraps __dict__

Display a decimal in scientific notation

This worked best for me:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10

SSL certificate is not trusted - on mobile only

Put your domain name here: You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

How Big can a Python List Get?

I got this from here on a x64 bit system: Python 3.7.0b5 (v3.7.0b5:abb8802389, May 31 2018, 01:54:01) [MSC v.1913 64 bit (AMD64)] on win32

enter image description here

Understanding React-Redux and mapStateToProps()

Yes, you can do this. You can also even process the state and return the object.

function mapStateToProps(state){  
  let completed = someFunction (state);
   return {
     completed : completed,  

This would be useful if you want to shift the logic related to state from render function to outside of it.

How to set env variable in Jupyter notebook

A gotcha I ran into: The following two commands are equivalent. Note the first cannot use quotes. Somewhat counterintuitively, quoting the string when using %env VAR ... will result in the quotes being included as part of the variable's value, which is probably not what you want.

%env MYPATH=C:/Folder Name/file.txt


import os
os.environ['MYPATH'] = "C:/Folder Name/file.txt"

Choose folders to be ignored during search in VS Code

Exclude all from subfolders works like this (version 2019)





How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.


<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

How to check if user input is not an int value

This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.

int counter = 1;
    System.out.println("Enter a number:");
    Scanner OddInput = new Scanner(;
            int Num = OddInput.nextInt();
            if (Num %2==0){
                System.out.println("Number " + Num + " is Even");
                System.out.println("Enter a number:");
            else {
                System.out.println("Number " + Num + " is Odd");
                System.out.println("Enter a number:");
        System.out.println("Program Ended");

Can I hide the HTML5 number input’s spin box?

I've encountered this problem with a input[type="datetime-local"], which is similar to this problem.

And I've found a way to overcome this kind of problems.

First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"

Then you can see all shadowed DOM elements, for example, for <input type="number">, the full element with shadowed DOM is:

<input type="number">_x000D_
  <div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
    <div id="editing-view-port">_x000D_
      <div id="inner-editor"></div>_x000D_
    <div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_

shadow DOM of input[type="number"

And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.

Foreign key referring to primary keys across multiple tables?

Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).

Defining constant string in Java?

You can use

 public static final String HELLO = "hello";

if you have many string constants, you can use external property file / simple "constant holder" class

Regular expression field validation in jQuery

Unless you're looking for something specific, you can already do Regular Expression matching using regular Javascript with strings.

For example, you can do matching using a string by something like this...

var phrase = "This is a phrase";
phrase = phrase.replace(/is/i, "is not");

Is there something you're looking for other than just Regular Expression matching in general?

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

download a file from Spring boot rest service

public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
        @PathVariable String fileName, HttpServletRequest request) {
    // Load file as Resource
    Resource resource;

    String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
            + "\\";
    Path path = Paths.get(fileBasePath + fileName);
    try {
        resource = new UrlResource(path.toUri());
    } catch (MalformedURLException e) {
        return null;

    // Try to determine file's content type
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (IOException ex) {
        System.out.println("Could not determine file type.");

    // Fallback to the default content type if type could not be determined
    if (contentType == null) {
        contentType = "application/octet-stream";

    return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")

To test it, use postman


an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

How to create a custom exception type in Java?

An exception is a class like any other class, except that it extends from Exception. So if you create your own class

public class MyCustomException extends Exception

you can throw such an instance with

   throw new MyCustomException( ... );
   //using whatever constructor params you decide to use

And this might be an interesting read

In git, what is the difference between merge --squash and rebase?

Let's start by the following example:

enter image description here

Now we have 3 options to merge changes of feature branch into master branch:

  1. Merge commits
    Will keep all commits history of the feature branch and move them into the master branch
    Will add extra dummy commit.

  2. Rebase and merge
    Will append all commits history of the feature branch in the front of the master branch
    Will NOT add extra dummy commit.

  3. Squash and merge
    Will group all feature branch commits into one commit then append it in the front of the master branch
    Will add extra dummy commit.

You can find below how the master branch will look after each one of them.

enter image description here

In all cases:
We can safely DELETE the feature branch.

What does "static" mean in C?

Static variables in C have the lifetime of the program.

If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.

For example:

void function()
    static int var = 1;
    printf("%d", var);

int main()
    function(); // Call 1
    function(); // Call 2

In the above program, var is stored in the data segment. Its lifetime is the whole C program.

After function call 1, var becomes 2. After function call 2, var becomes 3.

The value of var is not destroyed between functions calls.

If var had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var is also destroyed.

Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.

Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.

To try this:


static int x;

int main()
    printf("Accessing in same file%d", x):


    extern int x;
        printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c

run gcc -c file1.c

gcc -c file2.c

Now try to link them using:

gcc -o output file1.o file2.o

It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.



Convert object to JSON in Android

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);

How to view/delete local storage in Firefox?

From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings

Once there, you can enable the Storage options under Default Firefox Developer tools

Updated 27-3-16

Firefox 48.0a1 now supports Cookies editing.

Updated 3-4-16

Firefox 48.0a1 now supports localStorage and sessionStorage editing.

Updated 02-08-16

Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB

Declaring a custom android UI element using XML

The Android Developer Guide has a section called Building Custom Components. Unfortunately, the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:

1. Declare attributes in values\attrs.xml

<?xml version="1.0" encoding="utf-8"?>
    <declare-styleable name="MyCustomView">
        <attr name="android:text"/>
        <attr name="android:textColor"/>            
        <attr name="extraInformation" format="string" />

Notice the use of an unqualified name in the declare-styleable tag. Non-standard android attributes like extraInformation need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.

2. Create constructors

Since there are two constructors that use an AttributeSet for initialisation, it is convenient to create a separate initialisation method for the constructors to call.

private void init(AttributeSet attrs) { 
    TypedArray a=getContext().obtainStyledAttributes(

    //Use a
         R.styleable.MyCustomView_android_textColor, Color.BLACK));

    //Don't forget this

R.styleable.MyCustomView is an autogenerated int[] resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, R.styleable.MyCustomView_android_text contains the android_text attribute for MyCustomView. Attributes can then be retrieved from the TypedArray using various get functions. If the attribute is not defined in the defined in the XML, then null is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.

If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr, while attributes for this project are in R.attr.

int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};

Please note that you should not use anything in android.R.styleable, as per this thread it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.

3. Use it in a layout files such as layout\main.xml

Include the namespace declaration xmlns:app="" in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see this article for more info). The URL is simply a manner of uniquely identifying schemas - nothing actually needs to be hosted at that URL. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.

    android:text="Test text"
    app:extraInformation="My extra information"

Reference the custom view using the fully qualified name.

Android LabelView Sample

If you want a complete example, look at the android label view sample.

 TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);


<declare-styleable name="LabelView">
    <attr name="text"format="string"/>
    <attr name="textColor"format="color"/>
    <attr name="textSize"format="dimension"/>


    app:text="Blue" app:textSize="20dp"/>

This is contained in a LinearLayout with a namespace attribute: xmlns:app=""


Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You define var scatterSeries = [];, and then try to parse it as a json string at; which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.

How to delete mysql database through shell command

Try the following command:

mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]

How to declare a local variable in Razor?

I think you were pretty close, try this:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>

What's the canonical way to check for type in Python?

Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.

class Bomb:
    def __init__(self):

    def talk(self):

    def explode(self):
        print "BOOM!, The bomb explodes."

class Duck:
    def __init__(self):
    def talk(self):
        print "I am a duck, I will not blow up if you ask me to talk."    

class Kid:
    kids_duck = None

    def __init__(self):
        print "Kid comes around a corner and asks you for money so he could buy a duck."

    def takeDuck(self, duck):
        self.kids_duck = duck
        print "The kid accepts the duck, and happily skips along"

    def doYourThing(self):
        print "The kid tries to get the duck to talk"

myKid = Kid()
myBomb = Bomb()

Get value from a string after a special character

You can use .indexOf() and .substr() like this:

var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)

You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:

var myString = $("input").val().split("?").pop();

How to hide the keyboard when I press return key in a UITextField?

Swift 4

Set delegate of UITextField in view controller, field.delegate = self, and then:

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // don't force `endEditing` if you want to be asked for resigning
        // also return real flow value, not strict, like: true / false
        return textField.endEditing(false)

Bootstrap 3 collapsed menu doesn't close on click

Bootstrap's default setting is to keep the menu open when you click on a menu item. You can manually override this behaviour by calling .collapse('hide'); on the jQuery element that you want to collapse.

How do I convert a String to an InputStream in Java?

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

Android toolbar center title and custom font

A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:

Add to styles.xml:

<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#FF202230</item>
    <item name="android:fontFamily">@font/varela_round_regular</item>

In your res folder create a font folder (Ex: varela_round_regular.ttf)

Read the official guide to find out more

How to get all the AD groups for a particular user?

You should use System.DirectoryServices.AccountManagement. It's much easier. Here is a nice code project article giving you an overview on all the classes in this DLL.

As you pointed out, your current approach doesn't find out the primary group. Actually, it's much worse than you thought. There are some more cases that it doesn't work, like the domain local group from another domain. You can check here for details. Here is how the code looks like if you switch to use System.DirectoryServices.AccountManagement. The following code can find the immediate groups this user assigned to, which includes the primary group.

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext (ContextType.Domain, ""), IdentityType.SamAccountName, "username");
foreach (GroupPrincipal group in user.GetGroups())

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

It is actually a permission issue. Add these lines in your platforms/android/AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

How can I escape white space in a bash loop list?

To add to what Jonathan said: use the -print0 option for find in conjunction with xargs as follows:

find test/* -type d -print0 | xargs -0 command

That will execute the command command with the proper arguments; directories with spaces in them will be properly quoted (i.e. they'll be passed in as one argument).

Can't install any package with node npm

If you're unlucky enough to be switching back and forth from a network behind a proxy and a network NOT behind a proxy, you may have forgotten that your NPM config is set to expect a proxy.

For me, I had to open up ~/.npmrc and comment out my proxy settings (while at home) and vice versa while at work (behind the proxy).

Setting up and using environment variables in IntelliJ Idea

Path Variables dialog has nothing to do with the environment variables.

Environment variables can be specified in your OS or customized in the Run configuration:


HTTP Ajax Request via HTTPS Page

Still, this can be done with the following steps:

  1. send an https ajax request to your web-site (the same domain)

        'url'      : '//',
        'type'     : 'get',
        'data'     : {'foo' : 'bar'},
        'success'  : function(response) {
            console.log('Successful request');
    }).fail(function(xhr, err) {
        console.error('Request error');
  2. get ajax request, for example, by php, and make a CURL get request to any desired website via http.

    use linslin\yii2\curl;
    $curl = new curl\Curl();

Pass a javascript variable value into input type hidden value

//prompts for input in javascript
test=prompt("Enter a value?","some string");

//passes javascript to a hidden field.
document.getElementById('myField').value = test;

//prompts for input in javascript
test2=prompt("Enter a value?","some string2");

//passes javascript to a hidden field
document.getElementById('myField').value = test2;

//prints output
document.write("hello, "+test+test2;

now this is confusing but this should work...

Redirecting unauthorized controller in ASP.NET MVC

You should build your own Authorize-filter attribute.

Here's mine to study ;)

Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
    Private _role As String

    Public Property Role() As String
            Return Me._role
        End Get
        Set(ByVal value As String)
            Me._role = value
        End Set
    End Property

    Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        If Not String.IsNullOrEmpty(Me.Role) Then
            If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
                Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
                Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
                Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

                filterContext.HttpContext.Response.Redirect(loginUrl, True)
                Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
                If Not hasAccess Then
                    Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
                End If
            End If
            Throw New InvalidOperationException("No Role Specified")
        End If

    End Sub
End Class

How do I zip two arrays in JavaScript?

Use the map method:

var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
var c =, i) {_x000D_
  return [e, b[i]];_x000D_


How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

How do I change the owner of a SQL Server database?

Here is a way to change the owner on ALL DBS (excluding System)

EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
 exec sp_changedbowner ''sa''

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

.nowrap {_x000D_
  white-space: nowrap ;_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;

Display all dataframe columns in a Jupyter Python Notebook

I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

You can do the same for the rows too:

pd.set_option('display.max_rows', <number of rows>)

This saves importing IPython, and there are more options in the pandas.set_option documentation:

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This issue can happen not only in but also in any of the .

On systems, in my case, this issue arose when the shift and insert key was pressed in tandem unintentionally which takes the user to the overwrite mode.

To get back to insert mode you need to press shift and insert in tandem again.

XSD - how to allow elements in any order any number of times?

But from what I understand xs:choice still only allows single element selection. Hence setting the MaxOccurs to unbounded like this should only mean that "any one" of the child elements can appear multiple times. Is this accurate?

No. The choice happens individually for every "repetition" of xs:choice that occurs due to maxOccurs="unbounded". Therefore, the code that you have posted is correct, and will actually do what you want as written.

How to create an object property from a variable value in JavaScript?

You could just use this:

function createObject(propName, propValue){
    this[propName] = propValue;
var myObj1 = new createObject('string1','string2');

Anything you pass as the first parameter will be the property name, and the second parameter is the property value.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my file now has the following addition


Thanks for the heads up as to how to do this, Benjamin.

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
            using (SqlDataAdapter da = new SqlDataAdapter())
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
        catch (SQLException ex)
            Console.WriteLine("SQL Error: " + ex.Message);
        catch (Exception e)
            Console.WriteLine("Error: " + e.Message);
    return new DataSet();

The following is the sample of connection string in config file

    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />

CONVERT Image url to Base64

This is your html-

    <img id="imageid" src="">
    <canvas id="imgCanvas" />

Javascript should be-

   var can = document.getElementById("imgCanvas");
   var img = document.getElementById("imageid");
   var ctx = can.getContext("2d");
   ctx.drawImage(img, 10, 10);
   var encodedBase = can.toDataURL();

'encodedBase' Contains Base64 Encoding of Image.

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source:; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here:

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")





How to install pip for Python 3.6 on Ubuntu 16.10?

This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.

A short summary:

sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2


$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

Then to select python 3.6 run

sudo update-alternatives --config python3

and select '2'. Then

$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

To update pip select the desired version and

pip3 install --upgrade pip

$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Tested on Ubuntu 16.04.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

I have just installed asterisk 13.18.5 on CentOS7. After logging in as root, I was having the same problem and I just did "SELINUX=disabled" in /var/selinux/config and that was all. My asterisk started in verbose mode by doing asterisk -rvvvvvv. No errors !!!

Another way to get it done is to use "asterisk -&" command first and then wait for a while for an "OK" message from asterisk and then "asterisk -rvvvvv"

How to make Sonar ignore some classes for codeCoverage metric?

I am able to achieve the necessary code coverage exclusions by updating jacoco-maven-plugin configuration in pom.xml


this configuration excludes the and in the jacoco coverage.

And the following two lines does the same for sonar coverage .

    <sonar.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.</sonar.exclusions>
        <sonar.coverage.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.* </sonar.coverage.exclusions>

How do I select an entire row which has the largest ID in the table?

FROM table 

Change limit for "Mysql Row size too large"

Set followings on your my.cnf file and restart mysql server.


How can I tell if a DOM element is visible in the current viewport?

I find that the accepted answer here is overly complicated for most use cases. This code does the job well (using jQuery) and differentiates between fully visible and partially visible elements:

var element         = $("#element");
var topOfElement    = element.offset().top;
var bottomOfElement = element.offset().top + element.outerHeight(true);
var $window         = $(window);

$window.bind('scroll', function() {

    var scrollTopPosition   = $window.scrollTop()+$window.height();
    var windowScrollTop     = $window.scrollTop()

    if (windowScrollTop > topOfElement && windowScrollTop < bottomOfElement) {
        // Element is partially visible (above viewable area)
        console.log("Element is partially visible (above viewable area)");

    } else if (windowScrollTop > bottomOfElement && windowScrollTop > topOfElement) {
        // Element is hidden (above viewable area)
        console.log("Element is hidden (above viewable area)");

    } else if (scrollTopPosition < topOfElement && scrollTopPosition < bottomOfElement) {
        // Element is hidden (below viewable area)
        console.log("Element is hidden (below viewable area)");

    } else if (scrollTopPosition < bottomOfElement && scrollTopPosition > topOfElement) {
        // Element is partially visible (below viewable area)
        console.log("Element is partially visible (below viewable area)");

    } else {
        // Element is completely visible
        console.log("Element is completely visible");

How to get the date from the DatePicker widget in Android?

I manged to set the MinDate & the MaxDate programmatically like this :

    final Calendar c = Calendar.getInstance();

    int maxYear = c.get(Calendar.YEAR) - 20; // this year ( 2011 ) - 20 = 1991
    int maxMonth = c.get(Calendar.MONTH);
    int maxDay = c.get(Calendar.DAY_OF_MONTH);

    int minYear = 1960;
    int minMonth = 0; // january
    int minDay = 25;

    public void onCreate(Bundle savedInstanceState)
        BirthDateDP = (DatePicker) findViewById(;
        BirthDateDP.init(maxYear - 10, maxMonth, maxDay, new OnDateChangedListener()

        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
            if (year < minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (monthOfYear < minMonth && year == minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
                view.updateDate(minYear, minMonth, minDay);

                if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }}); // BirthDateDP.init()
    } // activity

it works fine for me, enjoy :)

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

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

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

Get the value of checked checkbox?

$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    if (':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
<script src=""></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">

Difference between volatile and synchronized in Java


There are 3 main issues with multithreading:

1) Race Conditions

2) Caching / stale memory

3) Complier and CPU optimisations

volatile can solve 2 & 3, but can't solve 1. synchronized/explicit locks can solve 1, 2 & 3.


1) Consider this thread unsafe code:


While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.

Using synchronized on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x was 1, and 2 threads try to preform x++ we know in the end it will be equal to 3. So it solves the race condition problem.

synchronized (this) {
   x++; // no problem now

Marking x as volatile does not make x++; atomic, so it doesn't solve this problem.

2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.

Consider that on one thread, x = 10;. And somewhat later, in another thread, x = 20;. The change in value of x might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20) the answer will be false.

Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.

Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.

3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.

Consider the following code:

boolean b = false;
int x = 10;

void threadA() {
    x = 20;
    b = true;

void threadB() {
    if (b) {

You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b to true), as b is set to true only after x is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b as volatile ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.

Note that before Java 5 New Memory Model, volatile didn’t solve this issue.

How to convert JSON to XML or XML to JSON?

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

angular.js ng-repeat li items with html content

use ng-bind-html-unsafe

it will apply html with text inside like below:

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}

What's a clean way to stop mongod on Mac OS X?

The solutions provided by others used to work for me but is not working for me anymore, which is as below.

brew services stop mongodb
brew services start mongodb

brew services list gives

Name              Status  User      Plist
mongodb-community started XXXXXXXXX /Users/XXXXXXXXX/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

So I used mongodb-community instead of mongodb which worked for me

brew services stop mongodb-community
brew services start mongodb-community

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

Python: how to capture image from webcam on click using OpenCV

Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame =
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # the frame!
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
# 8. shutdown the camera

You can see my github code here

Delete ActionLink with confirm dialog

Any click event before for update /edit/delete records message box alerts the user and if "Ok" proceed for the action else "cancel" remain unchanged. For this code no need to right separate java script code. it works for me

<a asp-action="Delete" asp-route-ID="@Item.ArtistID" onclick = "return confirm('Are you sure you wish to remove this Artist?');">Delete</a>

Quicker way to get all unique values of a column in VBA?

Try this

Option Explicit

Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long

myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs

Set uniqueRng = GetUniqueValues(ws, myCol)

End Sub

Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long

With ws
    .Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo

    firstRow = 1
    If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row

    Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With

End Function

it should be quite fast and without the drawback NeepNeepNeep told about

Java Look and Feel (L&F)

You can also use JTattoo (, it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:


Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel


Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.


position: absolute;


position: fixed;

W3C specifications for position: absolute and for position: fixed.

Generating UML from C++ code?

StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

if you are interested in a ready solution then you may look at HumanizerCpp library ( - it is a port of C# Humanizer library and it does exactly what you want.

It can even convert to ordinals and currently supports 3 languages: English, German and Russian.


const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );

std::cout << e->Convert( 123 ) << std::endl;
std::cout << e->Convert( 1234 ) << std::endl;
std::cout << e->Convert( 12345 ) << std::endl;
std::cout << e->Convert( 123456 ) << std::endl;

std::cout << std::endl;
std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;

const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );

std::cout << std::endl;
std::cout << g->Convert( 123456 ) << std::endl;

const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );

std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;


one hundred and twenty-three
one thousand two hundred and thirty-four
twelve thousand three hundred and forty-five
one hundred and twenty-three thousand four hundred and fifty-six

thousand and first
thousand and twenty-first

???? ?????? ??? ???????????

In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.

Regards, Serge

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");


Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

Put icon inside input element in a form

You Can Try this : Bootstrap-4 Beta

<div class="container">
                <div class="row">
                    <div class="input-group mb-3 col-sm-6">
                      <input type="text" class="form-control border-right-0" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
                        <div class="input-group-prepend bg-white">
                            <span class="input-group-text border-left-0 rounded-right bg-white" id="basic-addon1"><i class="fas fa-search"></i></span>


How do I discard unstaged changes in Git?

simply say

git stash

It will remove all your local changes. You also can use later by saying

git stash apply 

or git stash pop

How to send multiple data fields via Ajax?

Try with quotes:

data: {"status": status, "name": name}

It must work fine.

Run a controller function whenever a view is opened/shown

Following up on the answer and link from AlexMart, something like this works:

.controller('MyCtrl', function($scope) {
  $scope.$on('$ionicView.enter', function() {
     // Code you want executed every time view is opened

How to convert Base64 String to javascript file object like as from file input form?

I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.

const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
    mimeType = 'image/jpeg';
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
const file = new File([u8arr], imgName, {type: mimeType});

My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.

Hope this helps connects the dots for others.

How to initialize an array's length in JavaScript?

[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]


// [0, 0, 0, 0, 0, 0]

Note: you can't loop empty slots i.e. Array(4).forEach(() => …)


( typescript safe )

Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]


Classic method using a function ( works in any browser )

function NewArray(size) {
    var x = [];
    for (var i = 0; i < size; ++i) {
        x[i] = i;
    return x;

var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating nested arrays

When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.

var a = Array(3).fill([6]);
// [  [6], [6], [6]  ]

// [  [6, 9], [6, 9], [6, 9]  ]


var a = [...Array(3)].map(x => []);

a[0].push(4, 2);
// [  [4, 2], [], []  ]

So a 3x2 Array will look something like this:

[...Array(3)].map(x => Array(2).fill(0));
// [  [0, 0], [0, 0], [0, 0]  ]

N-dimensional array

function NArray(...dimensions) {
    var index = 0;
    function NArrayRec(dims) {
        var first = dims[0], next = dims.slice().splice(1); 
        if(dims.length > 1) 
            return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
        return Array(dims[0]).fill(null).map((x, i) => (index++));
    return NArrayRec(dimensions);

var arr = NArray(3, 2, 4);
// [   [  [ 0,  1,  2,  3 ] , [  4,  5,  6,  7]  ],
//     [  [ 8,  9,  10, 11] , [ 12, 13, 14, 15]  ],
//     [  [ 16, 17, 18, 19] , [ 20, 21, 22, 23]  ]   ]

Initialize a chessboard

var Chessboard = [...Array(8)].map((x, j) => {
    return Array(8).fill(null).map((y, i) => {
        return `${String.fromCharCode(65 + i)}${8 - j}`;

// [ [A8, B8, C8, D8, E8, F8, G8, H8],
//   [A7, B7, C7, D7, E7, F7, G7, H7],
//   [A6, B6, C6, D6, E6, F6, G6, H6],
//   [A5, B5, C5, D5, E5, F5, G5, H5],
//   [A4, B4, C4, D4, E4, F4, G4, H4],
//   [A3, B3, C3, D3, E3, F3, G3, H3],
//   [A2, B2, C2, D2, E2, F2, G2, H2],
//   [A1, B1, C1, D1, E1, F1, G1, H1] ]

Math filled values

handy little method overload when working with math

function NewArray( size , method, linear )
    method = method || ( i => i ); 
    linear = linear || false;
    var x = [];
    for( var i = 0; i < size; ++i )
        x[ i ] = method( linear ? i / (size-1) : i );
    return x;

NewArray( 4 ); 
// [ 0, 1, 2, 3 ]

NewArray( 4, Math.sin ); 
// [ 0, 0.841, 0.909, 0.141 ]

NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]

var pow2 = ( x ) => x * x;

NewArray( 4, pow2 ); 
// [ 0, 1, 4, 9 ]

NewArray( 4, pow2, true ); 
// [ 0, 0.111, 0.444, 1 ]

Maven artifact and groupId naming

However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.

com means this project belongs to a company, and org means this project belongs to a social organization. These are alright, but for those strange domain like,,, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.

Background blur with CSS

In which way do you want it dynamic? If you want the popup to successfully map to the background, you need to create two backgrounds. It requires both the use of element() or -moz-element() and a filter (for Firefox, use a SVG filter like filter: url(#svgBlur) since Firefox does not support -moz-filter: blur() as yet?). It only works in Firefox at the time of writing.

See demo here.

I still need to create a simple demo to show how it is done. You're welcome to view the source.

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1


Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:


This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

How to make a simple image upload using Javascript/HTML

<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">

<script type"text/javascript">
  function preview_image(event) {
    var reader = new FileReader();
    reader.onload = function(){
      var output = document.getElementById('output_image');
      output.src = reader.result;

Eclipse: Enable autocomplete / content assist

If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:

  1. Eclipse > Preferences > Java > Editor > Content Assist
  2. Auto Activation > Auto activation triggers for Java
  3. Enter all the characters you want to trigger autocomplete, such as the following:


Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.

Simplest way to throw an error/exception with a custom message in Swift 2?

The simplest approach is probably to define one custom enum with just one case that has a String attached to it:

enum MyError: ErrorType {
    case runtimeError(String)

Or, as of Swift 4:

enum MyError: Error {
    case runtimeError(String)

Example usage would be something like:

func someFunction() throws {
    throw MyError.runtimeError("some message")
do {
    try someFunction()
} catch MyError.runtimeError(let errorMessage) {

If you wish to use existing Error types, the most general one would be an NSError, and you could make a factory method to create and throw one with a custom message.

Convert a number range to another range, maintaining ratio

That's a simple linear conversion.

new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min

So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:

old_value = 10000
old_min = -16000
old_max = 16000
new_min = 0
new_max = 100

new_value = ( ( 10000 - -16000 ) / (16000 - -16000) ) * (100 - 0) + 0
          = 81.25

How to enable mod_rewrite for Apache 2.2

In Ubuntu:


a2enmod rewrite

and then:

service apache2 restart

mod_rewrite will now be enabled!

Bash scripting missing ']'

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix Then, run the script.

Array Size (Length) in C#

In most of the general cases 'Length' and 'Count' are used.


int[] myArray = new int[size];
int noOfElements = myArray.Length;

Typed List Array:

List <int> myArray = new List<int>();
int noOfElements = myArray.Count;

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1

SQL - Query to get server's IP address

you can use command line query and execute in mssql:

exec xp_cmdshell 'ipconfig'

How exactly does <script defer="defer"> work?

UPDATED: 2/19/2016

Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.

Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4

The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.

The results may vary from browser to browser.

Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec

The W3C's definition of defer:

"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."

How can I center text (horizontally and vertically) inside a div block?

Really simple code that works for me! Just one line and your text will be centered horizontally.

  justify-content: center;

<Card.Footer className="card-body-padding center-horizontally">
  <label className="support-expand-text-light">Call or email Customer Support to change</label>

The output looks like this:

Please vote this answer if it works for just to spare some time of devs looking for easy solutions. Thanks! :)

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));!4/22115/1

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.


If you want to plot lines use

plot(t, type="l")

What is the difference between an annotated and unannotated tag?


The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current command session without removing it permanently, use the regular built-in set command - just put nothing after the equals sign:


To confirm, run set with no arguments and check the current environment. The variable should be missing from the list entirely.

Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.

How to execute python file in linux

Add to top of the code,


Then, run the following command on the terminal,

chmod +x yourScriptFile

Limit number of characters allowed in form input text field

Make it simpler

<input type="text" maxlength="3" />

and use an alert to show that max chars have been used.

Android disable screen timeout while app is running

There is also a XML way that Google recommends:


Check Google Slides - Slide 16.

"Wakelocks are costly if forgotten (...) Consider using android:keepScreenOn to ensure correctness"

Can I recover a branch after its deletion in Git?

I used the following commands to find and retrieve my deleted branch. The first steps are from gcb's description.

$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\  -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline

Now look for the git commit id (GIT-SHA) based on the commit comments and use it in the command below. Checkout a new branch called NEW-BRANCH with the previously found GIT-SHA:

$ git checkout -b NEW-BRANCH GIT-SHA

Replace the single quote (') character from a string

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended - works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)

add item to dropdown list in html using javascript

Try to use appendChild method:


How do I handle newlines in JSON?

According to the specification,

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).

As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

jQuery adding 2 numbers from input fields

Adding strings concatenates them:

> "1" + "1"

You have to parse them into numbers first:

/* parseFloat is used here. 
 * Because of it's not known that 
 * whether the number has fractional places.

var a = parseFloat($('#a').val()),
    b = parseFloat($('#b').val());

Also, you have to get the values from inside of the click handler:

$("submit").on("click", function() {
   var a = parseInt($('#a').val(), 10),
       b = parseInt($('#b').val(), 10);

Otherwise, you're using the values of the textboxes from when the page loads.

ng-if, not equal to?

It is better to use ng-switch

<div ng-switch on="details.Payment[0].Status">
    <div ng-switch-when="1">
        <!-- code to render a large video block-->
    <div ng-switch-default>
        <!-- code to render the regular video block -->

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

Convert PDF to image with high resolution

I really haven't had good success with convert [update May 2020: actually: it pretty much never works for me], but I've had EXCELLENT success with pdftoppm. Here's a couple examples of producing high-quality images from a PDF:

  1. [Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc:

     mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg
  2. [Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI:

     mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg
  3. [Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI:

     mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg

For more explanations, options, and examples, see my full answer here:


  1. [How to turn a PDF into a searchable PDF w/pdf2searchablepdf]
  2. Cross-linked:
    1. How to convert a PDF into JPG with command line in Linux?

SQL query to select dates between two dates

You ca try this SQL

select * from employee where rec_date between '2017-09-01' and '2017-09-11' 

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Visual Studio 64 bit?

No! There is no 64-bit version of Visual Studio.

How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0

As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.

Color theme for VS Code integrated terminal

You can actually modify your user settings and edit each colour individually by adding the following to the user settings.

  1. Open user settings (ctrl + ,)
  2. Search for workbench and select Edit in settings.json under Color Customizations
"workbench.colorCustomizations" : {
    "terminal.foreground" : "#00FD61",
    "terminal.background" : "#383737"

For more on what colors you can edit you can find out here.

Remove a HTML tag but keep the innerHtml

You can also use .replaceWith(), like this:

$("b").replaceWith(function() { return $(this).contents(); });

Or if you know it's just a string:

$("b").replaceWith(function() { return this.innerHTML; });

This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly faster than the cost of .unwrap().

Best way to check for nullable bool in a condition expression (if ...)

Actually I think that (nullableBool ?? false) is a legitimate option especially when you are trying to evaluate a nullable bool in linq.

For example:

array.Select(v => v.nullableBool ?? false)
(from v in array where v.nullableBool ?? false)

Is cleaner in my opinion as opposed to:

array.Select(v => v.nullableBool.HasValue ? v.nullableBool.Value : false)
(from v in array where v.nullableBool.HasValue ? v.nullableBool.Value : false)

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

How do I use properly CASE..WHEN in MySQL

I think part of it is that you're stating the value you're selecting after CASE, and then using WHEN x = y syntax afterward, which is a combination of two different methods of using CASE. It should either be

  WHEN a THEN ...
  WHEN b THEN ...


  WHEN x = a THEN ...
  WHEN x = b THEN ...

How can I get a side-by-side diff when I do "git diff"?

If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff:

$ pip install webdiff
$ git webdiff

This offers a number of advantages over traditional GUI difftools like tkdiff in that it can give you syntax highlighting and show image diffs.

Read more about it here.

How to use wget in php?

Shellwrap is great tool for using the command-line in PHP!

Your example can be done quite easy and readable:

use MrRio\ShellWrap as sh;

$xml = (string)sh::curl(['u' => 'user:pass'], '');

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)


char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

Change icons of checked and unchecked for Checkbox for Android

Kind of a mix:

Set it in your layout file :-

 <CheckBox android:layout_width="wrap_content"
           android:text="new checkbox"
           android:button="@drawable/checkbox" />

where the @drawable/checkbox will look like:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />

How can I use querySelector on to pick an input element by name?

Note: if the name includes [ or ] itself, add two backslashes in front of it, like:

<input name="array[child]" ...


Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

Where do I configure log4j in a JUnit test class?

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

get parent's view from a layout

Just write


How do I expire a PHP session after 30 minutes?

This post shows a couple of ways of controlling the session timeout:

IMHO the second option is a nice solution:

 * Starts a session with a specific timeout and a specific GC probability.
 * @param int $timeout The number of seconds until it should time out.
 * @param int $probability The probablity, in int percentage, that the garbage 
 *        collection routine will be triggered right now.
 * @param strint $cookie_domain The domain path for the cookie.
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
    // Set the max lifetime
    ini_set("session.gc_maxlifetime", $timeout);

    // Set the session cookie to timout
    ini_set("session.cookie_lifetime", $timeout);

    // Change the save path. Sessions stored in teh same path
    // all share the same lifetime; the lowest lifetime will be
    // used for all. Therefore, for this to work, the session
    // must be stored in a directory where only sessions sharing
    // it's lifetime are. Best to just dynamically create on.
    $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
    $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
    if(!file_exists($path)) {
        if(!mkdir($path, 600)) {
            trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
    ini_set("session.save_path", $path);

    // Set the chance to trigger the garbage collection.
    ini_set("session.gc_probability", $probability);
    ini_set("session.gc_divisor", 100); // Should always be 100

    // Start the session!

    // Renew the time left until this session times out.
    // If you skip this, the session will time out based
    // on the time when it was created, rather than when
    // it was last used.
    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);

Why does AngularJS include an empty option in select?

i had the same problem, i (removed "ng-model") changed this :

<select ng-model="mapayear" id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}

to this:

<select id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}

now its working, but in my case it was cause ive deleted that scope from ng.controller, check if u didn't do the same.

Oracle's default date format is YYYY-MM-DD, WHY?

Oracle has both the Date and the Timestamp data types.

According to Oracle documentation, there are differences in data size between Date and Timestamp, so when the intention is to have a Date only field it makes sense to show the Date formatting. Also, "It does not have fractional seconds or a time zone." - so it is not the best choice when timestamp information is required.

The Date field can be easily formatted to show the time component in the Oracle SQL Developer - Date query ran in PL/SQL Developer shows time, but does not show in Oracle SQL Developer. But it won't show the fractional seconds or the time zone - for this you need Timestamp data type.

No Such Element Exception?

Looks like your line in the while loop is throwing the NoSuchElementException since the scanner reached the end of file. Read the next() java API here

Also you should not call next() in the loop and also in the while condition. In the while condition you should check if next token is available and inside the while loop check if its equal to treasure.

Pass Model To Controller using Jquery/Ajax

Use the following JS:

$(document).ready(function () {
    $("#btnsubmit").click(function () {

                 type: "POST",
                 url: '/Plan/PlanManage',     //your action
                 data: $('#PlanForm').serialize(),   //your form takes all the values of model               
                 dataType: 'json',
                 success: function (result) {
        return false;

and the following code on your controller:

public string PlanManage(Plan objplan)  //model plan