Programs & Examples On #App bundle

Converting Integers to Roman Numerals - Java

After seeing some of the answers here I had to post this. I think that my algorithm is far the most easiest to understand and the bit of performance lost is not important even on a relatively large scale. I'm also obeying the standardized coding conventions as opposed to some of the users here.

Average conversion time: 0.05ms (based on converting all numbers 1-3999 and dividing by 3999)

public static String getRomanNumeral(int arabicNumber) {

    if (arabicNumber > 0 && arabicNumber < 4000) {

        final LinkedHashMap<Integer, String> numberLimits = 
            new LinkedHashMap<>();

        numberLimits.put(1, "I");
        numberLimits.put(4, "IV");
        numberLimits.put(5, "V");
        numberLimits.put(9, "IX");
        numberLimits.put(10, "X");
        numberLimits.put(40, "XL");
        numberLimits.put(50, "L");
        numberLimits.put(90, "XC");
        numberLimits.put(100, "C");
        numberLimits.put(400, "CD");
        numberLimits.put(500, "D");
        numberLimits.put(900, "CM");
        numberLimits.put(1000, "M");

        String romanNumeral = "";

        while (arabicNumber > 0) {
            int highestFound = 0;
            for (Map.Entry<Integer, String> current : numberLimits.entrySet()){
                if (current.getKey() <= arabicNumber) {
                    highestFound = current.getKey();
            romanNumeral += numberLimits.get(highestFound);
            arabicNumber -= highestFound;

        return romanNumeral;

    } else {
        throw new UnsupportedOperationException(arabicNumber 
            + " is not a valid Roman numeral.");

First you have to take into account that Roman numerals are only in the interval of <1-4000), but that can be solved by a simple if and a thrown exception. Then you can try to find the largest set roman numeral in a given integer and if found subtract it from the original number and add it to the result. Repeat with the newly acquired number until you hit zero.

How to apply a function to two columns of Pandas dataframe

I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').

import numpy as np
import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below 

df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])


ID  col_1   col_2   col_3
0   1   0   1   [a, b]
1   2   2   4   [c, d, e]
2   3   3   5   [d, e, f]

Show space, tab, CRLF characters in editor of Visual Studio

Edit -> Advanced -> View White Space or Ctrl+E,S

Amazon Interview Question: Design an OO parking lot

you would need a parking lot, that holds a multi-dimensional array (specified in the constructor) of a type "space". The parking lot can keep track of how many spaces are taken via calls to functions that fill and empty spaces.Space can hold an enumerated type that tells what kind of space it is. Space also has a method taken(). for the valet parking, just find the first space thats open and put the car there. You will also need a Car object to put in the space, that holds whether it is a handicapped, compact, or regular vehicle.

class ParkingLot
    Space[][] spaces;

    ParkingLot(wide, long); // constructor

    FindOpenSpace(TypeOfCar); // find first open space where type matches

enum TypeOfSpace = {compact, handicapped, regular };
enum TypeOfCar = {compact, handicapped, regular };

class Space
    TypeOfSpace type;
    bool empty;
    // gets and sets here
    // make sure car type

class car
    TypeOfCar type;

Select a random sample of results from a query result

Suppose you are trying to select exactly 1,000 random rows from a table called my_table. This is one way to do it:

            row_number() over(order by dbms_random.value) as random_id,
            my_table x
    random_id <= 1000

This is a slight deviation from the answer posted by @Quassnoi. They both have the same costs and execution times. The only difference is that you can select the random number used to fetch the sample.

How do I trim whitespace from a string?

If you want to trim specified number of spaces from left and right, you could do this:

def remove_outer_spaces(text, num_of_leading, num_of_trailing):
    text = list(text)
    for i in range(num_of_leading):
        if text[i] == " ":
            text[i] = ""

    for i in range(1, num_of_trailing+1):
        if text[-i] == " ":
            text[-i] = ""
    return ''.join(text)

txt1 = "   MY name is     "
print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races


There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

How to analyse the heap dump using jmap in java

Very late to answer this, but worth to take a quick look at. Just 2 minutes needed to understand in detail.

First create this java program

import java.util.ArrayList;
import java.util.List;

public class GarbageCollectionAnalysisExample{
    public static void main(String[] args) {
           List<String> l = new ArrayList<String>();
           for (int i = 0; i < 100000000; i++) {
                  l = new ArrayList<String>(); //Memory leak

Use jps to find the vmid (virtual machine id i.e. JVM id)

Go to CMD and type below commands >

18588 Jps
17252 GarbageCollectionAnalysisExample
2084 Main

17252 is the vmid which we need.

Now we will learn how to use jmap and jhat

Use jmap - to generate heap dump

From java docs about jmap “jmap prints shared object memory maps or heap memory details of a given process or core file or a remote debug server”

Use following command to generate heap dump >

C:\>jmap -dump:file=E:\heapDump.jmap 17252
Dumping heap to E:\heapDump.jmap ...
Heap dump file created

Where 17252 is the vmid (picked from above).

Heap dump will be generated in E:\heapDump.jmap

Now use Jhat Jhat is used for analyzing the garbage collection dump in java -

C:\>jhat E:\heapDump.jmap
Reading from E:\heapDump.jmap...
Dump file created Mon Nov 07 23:59:19 IST 2016
Snapshot read, resolving...
Resolving 241865 objects...
Chasing references, expect 48 dots................................................
Eliminating duplicate references................................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

By default, it will start http server on port 7000. Then we will go to http://localhost:7000/

Courtesy : JMAP, How to monitor and analyze the garbage collection in 10 ways

How to properly add 1 month from now to current date in moment.js

var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');

if( != && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
    futureMonth = futureMonth.add(1, 'd');




moment.addRealMonth = function addRealMonth(d) {
  var fm = moment(d).add(1, 'M');
  var fmEnd = moment(fm).endOf('month');
  return != && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;  

var nextMonth = moment.addRealMonth(moment());


Setting default values for columns in JPA

This isn't possible in JPA.

Here's what you can do with the Column annotation:

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

Print a file, skipping the first X lines, in Bash

cat < File > | awk '{if(NR > 6) print $0}'

python convert list to dictionary

Not sure whether it would help you or not but it works to me:

l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))

How to click a browser button with JavaScript automatically?


Tracking CPU and Memory usage per process

Just type perfmon into Start > Run and press enter. When the Performance window is open, click on the + sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called "Performance Object".

For your questions, you can choose the "Process", "Memory" and "Processor" performance objects. You then can see these counters in real time

You can also specify the utility to save the performance data for your inspection later. To do this, select "Performance Logs and Alerts" in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click "File" > "Add/remove snap-in", click Add and select "Performance Logs and Alerts" in the list".) From the "Performance Logs and Alerts", create a new monitoring configuration under "Counter Logs". Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location.

Call angularjs function using jquery/javascript

Your plunker is firing off


Before anything is rendered.

You can verify that by wrapping it in a timeout

setTimeout(function() {
}, 1000);

You also need to acutally add an ID to your div.

<div ng-app='MyModule' ng-controller="MyController" id="MyController">

Clear variable in python

The del keyword would do.

>>> a=1
>>> a
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

But in this case I vote for self.left = None

Elasticsearch query to return all records

For Elasticsearch 6.x

Request: GET /foo/_search?pretty=true

Response: In Hits-> total, give the count of the docs

      "took": 1,
      "timed_out": false,
      "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
      "hits": {
        "total": 1001,
        "max_score": 1,
        "hits": [

How to Use slideDown (or show) function on a table row?

<table cellspacing='0' cellpadding='0' class='table01' id='form_table' style='width:100%;'>
    <td style='cursor:pointer; width:20%; text-align:left;' id='header'>
        <label style='cursor:pointer;'> <b id='header01'>? Customer Details</b>

    <td style='widtd:20%; text-align:left;'>
        <div id='content' class='content01'>
            <table cellspacing='0' cellpadding='0' id='form_table'>
                    <td>A/C ID</td>
                    <td>A/C ID</td>
                    <td>A/C ID</td>

$(function () {
$(".table01 td").on("click", function () {
    var $rows = $('.content01');
    if ($(".content01:first").is(":hidden")) {
        $("#header01").text("? Customer Details");
    } else {
        $("#header01").text("? Customer Details");


How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
return t1;

and now can be used like this:

table = GetDataTable();

Change the jquery show()/hide() animation?

Use slidedown():


How can I make my string property nullable?

As others have pointed out, string is always nullable in C#. I suspect you are asking the question because you are not able to leave the middle name as null or blank? I suspect the problem is with your validation attributes, most likely the RegEx. I'm not able to fully parse RegEx in my head but I think your RegEx insists on the first character being present. I could be wrong - RegEx is hard. In any case, try commenting out your validation attributes and see if it works, then add them back in one at a time.

How to call Stored Procedures with EntityFramework?

You have use the SqlQuery function and indicate the entity to mapping the result.

I send an example as to perform this:

var oficio= new SqlParameter
    ParameterName = "pOficio",
    Value = "0001"

using (var dc = new PCMContext())
    return dc.Database
             .SqlQuery<ProyectoReporte>("exec SP_GET_REPORTE @pOficio",

Token based authentication in Web API without any user interface

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true

All you have to do is to post URL encoded username and password inside query string.


If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You can try this solution :-

To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)

mysql -u root -p new_password

MySQLl access denied

In the Second link someone has commented the same problem.

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

Where can I find php.ini?

Run this in the command line:

php -r "echo php_ini_loaded_file().PHP_EOL;"

define a List like List<int,string>?

List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)

How can I search an array in VB.NET?

compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.

simple eg.

dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)

    if aNames(x) = sFind then y = x

y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:

z = 1
for x = 1 to length(aNames)
    if aNames(x) = sFind then 
        aIndexes(z) = x 
        z = z + 1

How to fast-forward a branch to head?

git checkout master
git pull

should do the job.

You will get the "Your branch is behind" message every time when you work on a branch different than master, someone does changes to master and you git pull.

(branch) $ //hack hack hack, while someone push the changes to origin/master
(branch) $ git pull   

now the origin/master reference is pulled, but your master is not merged with it

(branch) $ git checkout master
(master) $ 

now master is behind origin/master and can be fast forwarded

this will pull and merge (so merge also newer commits to origin/master)
(master) $ git pull 

this will just merge what you have already pulled
(master) $ git merge origin/master

now your master and origin/master are in sync

What are the differences between a clustered and a non-clustered index?

A clustered index actually describes the order in which records are physically stored on the disk, hence the reason you can only have one.

A Non-Clustered Index defines a logical order that does not match the physical order on disk.

"Proxy server connection failed" in google chrome

  1. Open Google Chrome.
  2. Click Menu on the upper right side. Beside the STAR symbol (Bookmark).
  3. Click Show Advanced Settings.
  4. Scroll down and find Network.
  5. Click Change proxy settings.
  6. On the Connections tab, click LAN settings.
  7. Uncheck "Use a proxy server for your LAN."
  8. Then click OK.

Hope it helps .

How to return a value from a Form in C#?

delegates are the best option for sending data from one form to another.

public partial class frmImportContact : Form
     public delegate void callback_data(string someData);
    public event callback_data getData_CallBack;

    private void button_Click(object sender, EventArgs e)
      string myData = "Top Secret Data To Share";


public partial class frmHireQuote : Form
     private void Button_Click(object sender, EventArgs e)

      frmImportContact obj = new frmImportContact();
      obj.getData_CallBack += getData;

    private void getData(string someData)

What's the best way to determine which version of Oracle client I'm running?

This is another, though not necessarily "better", way:

Determining Your Current Version

To determine which Oracle client version you have installed on your pc, run sql*plus to connect to the DW. The folder names may vary somewhat based on your Oracle setup but should be similar. To run sql*plus choose start > programs > Oracle > Oracle - OUDWclient > Application Development > sqlplus. Enter your DW user name, password, and 'ordj' for the host name or service name. This should connect you to the DW via sqlplus. At this point, you could write your own sql statements to pull information from the DW (if you knew sql). The Oracle client version can be determined in the first line - 'SQL*Plus: Release'.

[Reference] Oracle Client Information

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

How to concat string + i?

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));

How to read numbers from file in Python?

To make the answer simple here is a program that reads integers from the file and sorting them

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

After reading each line of the file converting each string to a digit


Sorting the numbers


f = open("input.txt", 'w')
for num in nums:
    f.write("%d\n" %num)


Writing them back As easy as that, Hope this helps

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

<SELECT multiple> - how to allow only one item selected?

Why don't you want to remove the multiple attribute? The entire purpose of that attribute is to specify to the browser that multiple values may be selected from the given select element. If only a single value should be selected, remove the attribute and the browser will know to allow only a single selection.

Use the tools you have, that's what they're for.

What's the difference between "2*2" and "2**2" in Python?





to see the difference.

** is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.

Server unable to read htaccess file, denying access to be safe

Ok, I recently met the same issue too while working on a WordPress installation using apache2 on the server on Ubuntu 20.04.

I experienced this issue when I changed file ownership to another user:

Here's what worked for me:

$ sudo chown -R www-data:www-data /var/www/YOUR-DIRECTORY

Here's a bit more context into the issue:

The above command gives ownership of all the files [in that folder] to the www-data user and group. This is the user that the Apache web server runs as, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates.

Be sure to point to your server’s relevant directory (replace YOUR-DIRECTORY with your actual folder).

You could run through this insightful article on digitalocean.

Microsoft Azure: How to create sub directory in a blob container

Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.

Note: $web container was created automatically while enable static website. Never seen $root container anywhere.

//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01

//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.


void MyFunc();


#include "other.h"
int main() {


#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

You can also do this in ASP.NET Core 2 by defining the connection string in your appSettings.json file. Then in your Startup.cs you specify which connection string to use.


    "connectionStrings": {
        "YourDBConnectionString": "Server=(localdb)\\mssqllocaldb;Database=YourDB;Trusted_Connection=True"


public static IConfiguration Configuration { get; private set;}

public Startup(IConfiguration configuration)
    Configuration = configuration;
var connectionString = Configuration["connectionStrings:YourDBConnectionString"];
services.AddDbContext<YourDbContext>(x => x.UseSqlServer(connectionString));

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

Only on Firefox "Loading failed for the <script> with source"

I had the same issue with firefox, when I searched for a solution I didn't find anything, but then I tried to load the script from a cdn, it worked properly, so I think you should try loading it from a cdn link, I mean if you are trying to load a script that you havn't created. because in my case, when tried to load a script that is mine, it worked and imported successfully, for now I don't know why, but I think there is something in the scripts from network, so just try cdn, you won't lose anything.

I wish it help you.

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:


and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

CSS change button style after click

If you're looking for a pure css option, try using the :focus pseudo class.

#style  {
    background-color: red;

#style:focus {     

Difference between $(document.body) and $('body')

The answers here are not actually completely correct. Close, but there's an edge case.

The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.

That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.

I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

This is the Different Solution, Check if your Services are running correctly, if WAMP icon showing orange color, and 2 out of 3 services are running it's showing, then this solution will work . Root cause:

If in your system mysql was there, later you installed WAMP then again one MYSQL will install as WAMP package, default port for MYSQL is 3306 , So in both mysql the port will be 3306, which is a port conflict, So just change the port it will work fine. Steps to change the Port.

  1. Right click the WAMP icon.
  2. Chose Tool
  3. Change the port in Port used by MySql Section

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)

Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

How do I resolve a TesseractNotFoundError?

I faced the same problem. I hope you have installed from here and have also done pip install pytesseract.

If everything is fine you should see that the path C:\Program Files (x86)\Tesseract-OCR where tesseract.exe is available.

Adding Path variable did not helped me, I actually added new variable with name tesseract in environment variables with a value of C:\Program Files (x86)\Tesseract-OCR\tesseract.exe.

Typing tesseract in the command line should now work as expected by giving you usage informations. You can now use pytesseract as such (don't forget to restart your python kernel before running this!):

import pytesseract
from PIL import Image"text_image.png")
text = pytesseract.image_to_string(value, config='')    
print("text present in images:",text)


Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How to refresh the data in a jqGrid?

This worked for me.

jQuery('#grid').jqGrid('setGridParam', {data: dataToLoad});

Byte array to image conversion

You haven't declared returnImage as any kind of variable :)

This should help:

public Image byteArrayToImage(byte[] byteArrayIn)
        MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
        ms.Write(byteArrayIn, 0, byteArrayIn.Length);
        Image returnImage = Image.FromStream(ms,true);
    catch { }
    return returnImage;

Check if an element contains a class in JavaScript?

in which element is currently the class '.bar' ? Here is another solution but it's up to you.

var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string

if (query.match(reg)) { // checks if it matches
  alert('the class .bar is attached to the following Element:\n' + query);

jsfiddle demo

Of course this is only a lookup for 1 simple element <img>(/Image/g) but you can put all in an array like <li> is /LI/g, <ul> = /UL/g etc.

CSS: fixed position on x-axis but not y?

Sounds like you need to use position:fixed and then set the the top position to a percentage and the and either the left or the right position to a fixed unit.

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

Old answer (applicable till 2016)

Here's an Apple developer link that explicitly says that -

on iPhone and iPod touch, which are small screen devices, "Video is NOT presented within the Web Page"

Safari Device-Specific Considerations

Your options:

  • The webkit-playsinline attribute works for HTML5 videos on iOS but only when you save the webpage to your home screen as a webapp - Not if opened a page in Safari
  • For a native app with a WebView (or a hybrid app with HTML, CSS, JS) the UIWebView allows to play the video inline, but only if you set the allowsInlineMediaPlayback property for the UIWebView class to true

How to show the text on a ImageButton?

you can use a regular Button and the android:drawableTop attribute (or left, right, bottom) instead.

Variables not showing while debugging in Eclipse

I used Fender's style above, but selected to "Watch" a variable. Once in the Expressions tab, I just moved over to the Variables tab and Voila - variables back in business.

CSS background-image-opacity?

Try this

<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat; background-position: center;"> </div>

How to show android checkbox at right side?

You can do

android:gravity="right|center"//or "center_vertical" for center text
android:text="hello" />

Following line is enough


Installing Android Studio, does not point to a valid JVM installation error

Most probably the issue happens because of the incompatability of 32 bit and 64 bit excecutables. Suppose if you have installed 32 bit Android Studio by mistake and you will be downloading a 64 bit JDK. In this case 32 bit Android Studio will not be able to pick up the 64 bit JDK. This was the issue I faced. So I followed the below simple steps to make it working,

  1. Downloaded 32 bit JDK(you can also download 64 bit Android Studio if you do not want to change the 64 bit JDK)
  2. Right click MyComputer > Advanced System Settings > under 'Advanced tab' > Environment variables > Under System Variables > Add JAVA_HOME as key and your jdk(eg:C:\Program Files (x86)\Java\jdk1.7.0_79) location as value.
  3. Save it and launch Android Studio. You are good to go now.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.


Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

fork() and wait() with two child processes

brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)

#include <sys/types.h>

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Array.size() vs Array.length

The property 'length' returns the (last_key + 1) for arrays with numeric keys:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ; nums.length );

will print 12!

This will work:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ;
nums [ 12 ]  =  12 ; nums.length + '  /  '+ Object.keys(nums).length );

How to calculate number of days between two given dates?

from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)

C++ Object Instantiation

The only reason I'd worry about is that Dog is now allocated on the stack, rather than the heap. So if Dog is megabytes in size, you may have a problem,

If you do need to go the new/delete route, be wary of exceptions. And because of this you should use auto_ptr or one of the boost smart pointer types to manage the object lifetime.

How to prevent a click on a '#' link from jumping to top of page?

You could just pass an anchor tag without an href property, and use jQuery to do the required action:

<a class="foo">bar</a>

How to get today's Date?

Use this code ;

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

This will shown as :

Feb 5, 2013 12:39:02PM

Validate email with a regex in jQuery

function mailValidation(val) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!expr.test(val)) {
        $('#errEmail').text('Please enter valid email.');
    else {

Access VBA | How to replace parts of a string with another string

Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.

Public Function strReplace(varValue As Variant) as Variant

Select Case varValue

    Case "Avenue"
        strReplace = "Ave"

    Case " North "
        strReplace = " N "

    Case Else
        strReplace = varValue

End Select

End Function

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.

jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        <div class="col-sm-6 my-column">
            Col 2

and the CSS

.row {
    border: blue 1px solid;
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
.my-column:first-child {
    background-color: red;

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;

css divide width 100% to 3 column

Using this fiddle, you can play around with the width of each div. I've tried in both Chrome and IE and I notice a difference in width between 33% and 33.3%. I also notice a very small difference between 33.3% and 33.33%. I don't notice any difference further than this.

The difference between 33.33% and the theoretical 33.333...% is a mere 0.00333...%.

For arguments sake, say my screen width is 1960px; a fairly high but common resolution. The difference between these two widths is still only 0.065333...px.

So, further than two decimal places, the difference in precision is negligible.

Can't build create-react-app project with custom PUBLIC_URL

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "",

You would just add it as one of the root fields in package.json, e.g.

  // ...
  "scripts": {
    // ...
  "homepage": ""

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at
You can control this with the homepage field in your package.json.

How to run shell script on host from docker container?

The solution I use is to connect to the host over SSH and execute the command like this:



As this answer keeps getting up votes, I would like to remind (and highly recommend), that the account which is being used to invoke the script should be an account with no permissions at all, but only executing that script as sudo (that can be done from sudoers file).

angularjs: ng-src equivalent for background-image:url(...)

just a matter of taste but if you prefer accessing the variable or function directly like this:

<div id="playlist-icon" back-img="playlist.icon">

instead of interpolating like this:

<div id="playlist-icon" back-img="{{playlist.icon}}">

then you can define the directive a bit differently with scope.$watch which will do $parse on the attribute

angular.module('myApp', [])
.directive('bgImage', function(){

    return function(scope, element, attrs) {
        scope.$watch(attrs.bgImage, function(value) {
                'background-image': 'url(' + value +')',
                'background-size' : 'cover'

there is more background on this here: AngularJS : Difference between the $observe and $watch methods

jQuery find element by data attribute value

Use Attribute Equals Selector


Fiddle Demo


it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Android Closing Activity Programmatically

you can use this.finish() if you want to close current activity.


IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    SELECT * FROM table
    WHERE column = ANY(subquery);

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

SQL Server: UPDATE a table by using ORDER BY

I ran into the same problem and was able to resolve it in very powerful way that allows unlimited sorting possibilities.

I created a View using (saving) 2 sort orders (*explanation on how to do so below).

After that I simply applied the update queries to the View created and it worked great.

Here are the 2 queries I used on the view:

1st Query:

Update  MyView
Set SortID=0

2nd Query:

DECLARE @sortID int
SET     @sortID = 0
SET     @sortID = sortID = @sortID + 1

*To be able to save the sorting on the View I put TOP into the SELECT statement. This very useful workaround allows the View results to be returned sorted as set when the View was created when the View is opened. In my case it looked like:

(NOTE: Using this workaround will place an big load on the server if using a large table and it is therefore recommended to include as few fields as possible in the view if working with large tables)

SELECT     TOP (600000) 
dbo.Items.ID, dbo.Items.Code, dbo.Items.SortID, dbo.Supplier.Date, 
dbo.Supplier.Code AS Expr1
FROM         dbo.Items INNER JOIN
                      dbo.Supplier ON dbo.Items.SupplierCode = dbo.Supplier.Code
ORDER BY dbo.Supplier.Date, dbo.Items.ID DESC

Running: SQL Server 2005 on a Windows Server 2003

Additional Keywords: How to Update a SQL column with Ascending or Descending Numbers - Numeric Values / how to set order in SQL update statement / how to save order by in sql view / increment sql update / auto autoincrement sql update / create sql field with ascending numbers

Manually type in a value in a "Select" / Drop-down HTML list?

It can be done now with HTML5

See this post here HTML select form with option to enter custom value

<input type="text" list="cars" />
<datalist id="cars">

The smallest difference between 2 Angles

x is the target angle. y is the source or starting angle:

atan2(sin(x-y), cos(x-y))

It returns the signed delta angle. Note that depending on your API the order of the parameters for the atan2() function might be different.

How to output loop.counter in python jinja template?

change this {% if loop.counter == 1 %} to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}

and this from {{ user }} {{loop.counter}} to {{ user }} {{forloop.counter}}

Rename multiple columns by names

With dplyr you would do:


df = data.frame(q = 1, w = 2, e = 3)
df %>% rename(A = q, B = e)

#  A w B
#1 1 2 3

Or if you want to use vectors, as suggested by @Jelena-bioinf:


df = data.frame(q = 1, w = 2, e = 3)

oldnames = c("q","e")
newnames = c("A","B")

df %>% rename_at(vars(oldnames), ~ newnames)

#  A w B
#1 1 2 3

L. D. Nicolas May suggested a change given rename_at is being superseded by rename_with:

df %>% 
  rename_with(~ newnames[which(oldnames == .x)], .cols = oldnames)

#  A w B
#1 1 2 3

:: (double colon) operator in Java 8

Double colon i.e. :: operator is introduced in Java 8 as a method reference. Method reference is a form of lambda expression which is used to refer the existing method by its name.



  • stream.forEach(element -> System.out.println(element))

By using Double Colon ::

  • stream.forEach(System.out::println(element))

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).

An example of a FIRST/FIRST conflict:

S -> Xb | Yc
X -> a 
Y -> a 

By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.

An example of a FIRST/FOLLOW conflict:

S -> AB 
A -> fe | epsilon 
B -> fg 

By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).

Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.

define() vs. const

define I use for global constants.

const I use for class constants.

You cannot define into class scope, and with const you can. Needless to say, you cannot use const outside class scope.

Also, with const, it actually becomes a member of the class, and with define, it will be pushed to global scope.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,


could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                        return Boolean.class;
        JScrollPane scrollPane = new JScrollPane(table);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setLocation(150, 150);

disable past dates on datepicker

This will work:

 var dateToday = new Date();    
 $(function () {
         minDate: dateToday 

T-SQL string replace in Update

If anyone cares, for NTEXT, use the following format:

    FROM [DataTable]

Liquibase lock - reasons?

In postgres 12 I needed to use this command:


UIButton: set image for selected-highlighted state

In swift you can do:

button.setImage(UIImage(named: "selected"), 
                forState: UIControlState.selected.union(.highlighted))

WebDriver: check if an element exists?

String link = driver.findElement(By.linkText(linkText)).getAttribute("href")

This will give you the link the element is pointing to.

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

How to validate domain credentials?

C# in .NET 3.5 using System.DirectoryServices.AccountManagement.

 bool valid = false;
 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
     valid = context.ValidateCredentials( username, password );

This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.

How to horizontally center an element

Make it simple!

#outer {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
<div id="outer">  _x000D_
  <div id="inner">Foo foo</div>_x000D_

How to write a multiline Jinja statement

According to the documentation: you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is not a standard header. Most commonly it refers to the header for Borland's BGI API for DOS and is antiquated at best.

However it is nicely simple; there is a Win32 implementation of the BGI interface called WinBGIm. It is implemented using Win32 GDI calls - the lowest level Windows graphics interface. As it is provided as source code, it is perhaps a simple way of understanding how GDI works.

WinBGIm however is by no means cross-platform. If all you want are simple graphics primitives, most of the higher level GUI libraries such as wxWidgets and Qt support that too. There are simpler libraries suggested in the possible duplicate answers mentioned in the comments.

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   

table td.wideRow, table th.wideRow{
width: 300px;

How to do 3 table JOIN in UPDATE query?

For PostgreSQL example:

SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE AND a.amount <> 0; 

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

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

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

For vs. while in C programming?

A for suggest a fixed iteration using an index or variants on this scheme.

A while and do... while are constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.

You can use either construct, but they have their advantages and disadvantages depending on your use case.

How to Find App Pool Recycles in Event Log

As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer

It is definitely System Log.

Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx.

You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.

You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"


Calculate percentage Javascript

For percent increase and decrease, using 2 different methods:

const a = 541
const b = 394

// Percent increase 
  `Increase (from ${b} to ${a}) => `,
  (((a/b)-1) * 100).toFixed(2) + "%",

// Percent decrease
  `Decrease (from ${a} to ${b}) => `,
  (((b/a)-1) * 100).toFixed(2) + "%",

// Alternatives, using .toLocaleString() 
  `Increase (from ${b} to ${a}) => `,
  ((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),

  `Decrease (from ${a} to ${b}) => `,
  ((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),

Before and After Suite execution hook in jUnit 4.x

A colleague of mine suggested the following: you can use a custom RunListener and implement the testRunFinished() method:

To register the RunListener just configure the surefire plugin as follows: section "Using custom listeners and reporters"

This configuration should also be picked by the failsafe plugin. This solution is great because you don't have to specify Suites, lookup test classes or any of this stuff - it lets Maven to do its magic, waiting for all tests to finish.

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function


What is the easiest/best/most correct way to iterate through the characters of a string in Java?

Two options

for(int i = 0, n = s.length() ; i < n ; i++) { 
    char c = s.charAt(i); 


for(char c : s.toCharArray()) {
    // process c

The first is probably faster, then 2nd is probably more readable.

Correct use for angular-translate in controllers

Actually, you should use the translate directive for such stuff instead.

<h1 translate="{{pageTitle}}"></h1>

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

However, if there's no way around and you really have to use $translate service in the controller, you should wrap the call in a $translateChangeSuccess event using $rootScope in combination with $translate.instant() like this:

.controller('foo', function ($rootScope, $scope, $translate) {
  $rootScope.$on('$translateChangeSuccess', function () {
    $scope.pageTitle = $translate.instant('PAGE.TITLE');

So why $rootScope and not $scope? The reason for that is, that in angular-translate's events are $emited on $rootScope rather than $broadcasted on $scope because we don't need to broadcast through the entire scope hierarchy.

Why $translate.instant() and not just async $translate()? When $translateChangeSuccess event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant() which is synchronous and just assumes that translations are available.

Since version 2.8.0 there is also $translate.onReady(), which returns a promise that is resolved as soon as translations are ready. See the changelog.

ComboBox SelectedItem vs SelectedValue

If we want to bind to a dictionary ie

  <ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                              ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
                              Margin="{StaticResource SmallMarginLeftBottom}"/>

then SelectedItem will not work whilist SelectedValue will

How To Remove Outline Border From Input Button

Another alternative to restore outline when using the keyboard is to use :focus-visible. However, this doesn't work on IE :

Reading an image file in C/C++

corona is nice. From the tutorial:

corona::Image* image = corona::OpenImage("img.jpg", corona::PF_R8G8B8A8);
if (!image) {
  // error!

int width  = image->getWidth();
int height = image->getHeight();
void* pixels = image->getPixels();

// we're guaranteed that the first eight bits of every pixel is red,
// the next eight bits is green, and so on...
typedef unsigned char byte;
byte* p = (byte*)pixels;
for (int i = 0; i < width * height; ++i) {
  byte red   = *p++;
  byte green = *p++;
  byte blue  = *p++;
  byte alpha = *p++;

pixels would be a one dimensional array, but you could easily convert a given x and y position to a position in a 1D array. Something like pos = (y * width) + x

Adding an assets folder in Android Studio

An image of how to in Android Studio 1.5.1.

Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...

enter image description here

Understanding SQL Server LOCKS on SELECT queries

I have to add an important comment. Everyone is mentioning that NOLOCKreads only dirty data. This is not precise. It is also possible that you'll get same row twice or whole row is skipped during your read. Reason is that you could ask for some data in same time when SQL Server is re-balancing b-tree.

Check another threads

With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice.

Ignore python multiple return value

The common practice is to use the dummy variable _ (single underscore), as many have indicated here before.

However, to avoid collisions with other uses of that variable name (see this response) it might be a better practice to use __ (double underscore) instead as a throwaway variable, as pointed by ncoghlan. E.g.:

x, __ = func()

How do I set up a private Git repository on GitHub? Is it even possible?

GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.

You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.

Redirect stderr to stdout in C shell

   xxx >& filename

Or do this to see everything on the screen and have it go to your file:

  xxx | & tee ./logfile

Need to navigate to a folder in command prompt

To access another drive, type the drive's letter, followed by ":".


Then enter:

cd d:\windows\movie

jQuery.inArray(), how to use it right?

It will return the index of the item in the array. If it's not found you will get -1

Run R script from command line

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))'
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")' 

How to sort a list of strings?

l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']


['abc', 'ba', 'cd', 'dc', 'xy']

Impersonate tag in Web.Config

Put the identity element before the authentication element

PHP script to loop through all of the files in a directory?

you can do this as well

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

In Linux, how to tell how much memory processes are using?

You can use pmap to report memory usage.


pmap [ -x | -d ] [ -q ] pids... 

How can I reverse a NSArray in Objective-C?

I don't know of any built in method. But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.

int n = [arr count];
for (int i=0; i<n/2; ++i) {
  id c  = [[arr objectAtIndex:i] retain];
  [arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
  [arr replaceObjectAtIndex:n-i-1 withObject:c];

Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').

NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];

Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.

chrome undo the action of "prevent this page from creating additional dialogs"

Close the tab of the page you disabled alerts. Re-open the page in a new tab. The setting only lasts for the session, so alerts will be re-enabled once the new session begins in the new tab.

Jquery select change not firing

Try this

$('body').on('change', '#multiid', function() {
    // your stuff

please check .on() selector

Adding HTML entities using CSS content

CSS is not HTML. &nbsp; is a named character reference in HTML; equivalent to the decimal numeric character reference &#160;. 160 is the decimal code point of the NO-BREAK SPACE character in Unicode (or UCS-2; see the HTML 4.01 Specification). The hexadecimal representation of that code point is U+00A0 (160 = 10 × 161 + 0 × 160). You will find that in the Unicode Code Charts and Character Database.

In CSS you need to use a Unicode escape sequence for such characters, which is based on the hexadecimal value of the code point of a character. So you need to write

.breadcrumbs a:before {
  content: '\a0';

This works as long as the escape sequence comes last in a string value. If characters follow, there are two ways to avoid misinterpretation:

a) (mentioned by others) Use exactly six hexadecimal digits for the escape sequence:

.breadcrumbs a:before {
  content: '\0000a0foo';

b) Add one white-space (e. g., space) character after the escape sequence:

.breadcrumbs a:before {
  content: '\a0 foo';

(Since f is a hexadecimal digit, \a0f would otherwise mean GURMUKHI LETTER EE here, or ? if you have a suitable font.)

The delimiting white-space will be ignored, and this will be displayed  foo, where the displayed space here would be a NO-BREAK SPACE character.

The white-space approach ('\a0 foo') has the following advantages over the six-digit approach ('\0000a0foo'):

  • it is easier to type, because leading zeroes are not necessary, and digits do not need to be counted;
  • it is easier to read, because there is white-space between escape sequence and following text, and digits do not need to be counted;
  • it requires less space, because leading zeroes are not necessary;
  • it is upwards-compatible, because Unicode supporting code points beyond U+10FFFF in the future would require a modification of the CSS Specification.

Thus, to display a space after an escaped character, use two spaces in the stylesheet –

.breadcrumbs a:before {
  content: '\a0  foo';

– or make it explicit:

.breadcrumbs a:before {
  content: '\a0\20 foo';

See CSS 2.1, section "4.1.3 Characters and case" for details.

In Python, what happens when you import inside of a function?

Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?

And then you can use profiling to assure that your optimizations have actually benefited you, too.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/;


fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/

So I need just socket, no any, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/;

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/;

Automatic login script for a website on windows machine?

From the term "automatic login" I suppose security (password protection) is not of key importance here.

The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).

The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:

// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("") > -1) {
    // Lets login to Gmail
    jQuery("#Email").val("[email protected]");

Now save this as say login.js

Then create a bookmark (in any browser) with this (as an) url:

javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");

Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.

Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with functionality to open more sites, but that may get the script inclusion more complicated.

Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.

Check element exists in array

`e` in ['a', 'b', 'c']  # evaluates as False
`b` in ['a', 'b', 'c']  # evaluates as True

EDIT: With the clarification, new answer:

Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0 to len(arr) - 1, so you can check whether your index is in that range. try/catch is a good way to do it pythonically, though.

If you're asking about the hash functionality of PHP "arrays" (Python's dict), then my previous answer still kind of stands:

`baz` in {'foo': 17, 'bar': 19}  # evaluates as False
`foo` in {'foo': 17, 'bar': 19}  # evaluates as True

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...

How to grab substring before a specified character jQuery or JavaScript

var newString = string.substr(0,string.indexOf(','));

Drawing a simple line graph in Java

Just complementing Hovercraft Full Of Eels's solution:

I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want.

Here is the Gist link, I'll also paste the code below: GraphPanel on Gist

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphPanel extends JPanel {

    private int width = 800;
    private int heigth = 400;
    private int padding = 25;
    private int labelPadding = 25;
    private Color lineColor = new Color(44, 102, 230, 180);
    private Color pointColor = new Color(100, 100, 100, 180);
    private Color gridColor = new Color(200, 200, 200, 200);
    private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
    private int pointWidth = 4;
    private int numberYDivisions = 10;
    private List<Double> scores;

    public GraphPanel(List<Double> scores) {
        this.scores = scores;

    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
        double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());

        List<Point> graphPoints = new ArrayList<>();
        for (int i = 0; i < scores.size(); i++) {
            int x1 = (int) (i * xScale + padding + labelPadding);
            int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
            graphPoints.add(new Point(x1, y1));

        // draw white background
        g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);

        // create hatch marks and grid lines for y axis.
        for (int i = 0; i < numberYDivisions + 1; i++) {
            int x0 = padding + labelPadding;
            int x1 = pointWidth + padding + labelPadding;
            int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
            int y1 = y0;
            if (scores.size() > 0) {
                g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
                String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
                FontMetrics metrics = g2.getFontMetrics();
                int labelWidth = metrics.stringWidth(yLabel);
                g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
            g2.drawLine(x0, y0, x1, y1);

        // and for x axis
        for (int i = 0; i < scores.size(); i++) {
            if (scores.size() > 1) {
                int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
                int x1 = x0;
                int y0 = getHeight() - padding - labelPadding;
                int y1 = y0 - pointWidth;
                if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
                    g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
                    String xLabel = i + "";
                    FontMetrics metrics = g2.getFontMetrics();
                    int labelWidth = metrics.stringWidth(xLabel);
                    g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
                g2.drawLine(x0, y0, x1, y1);

        // create x and y axes 
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);

        Stroke oldStroke = g2.getStroke();
        for (int i = 0; i < graphPoints.size() - 1; i++) {
            int x1 = graphPoints.get(i).x;
            int y1 = graphPoints.get(i).y;
            int x2 = graphPoints.get(i + 1).x;
            int y2 = graphPoints.get(i + 1).y;
            g2.drawLine(x1, y1, x2, y2);

        for (int i = 0; i < graphPoints.size(); i++) {
            int x = graphPoints.get(i).x - pointWidth / 2;
            int y = graphPoints.get(i).y - pointWidth / 2;
            int ovalW = pointWidth;
            int ovalH = pointWidth;
            g2.fillOval(x, y, ovalW, ovalH);

//    @Override
//    public Dimension getPreferredSize() {
//        return new Dimension(width, heigth);
//    }
    private double getMinScore() {
        double minScore = Double.MAX_VALUE;
        for (Double score : scores) {
            minScore = Math.min(minScore, score);
        return minScore;

    private double getMaxScore() {
        double maxScore = Double.MIN_VALUE;
        for (Double score : scores) {
            maxScore = Math.max(maxScore, score);
        return maxScore;

    public void setScores(List<Double> scores) {
        this.scores = scores;

    public List<Double> getScores() {
        return scores;

    private static void createAndShowGui() {
        List<Double> scores = new ArrayList<>();
        Random random = new Random();
        int maxDataPoints = 40;
        int maxScore = 10;
        for (int i = 0; i < maxDataPoints; i++) {
            scores.add((double) random.nextDouble() * maxScore);
//            scores.add((double) i);
        GraphPanel mainPanel = new GraphPanel(scores);
        mainPanel.setPreferredSize(new Dimension(800, 600));
        JFrame frame = new JFrame("DrawGraph");

    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {

It looks like this: Example pic

How to send a stacktrace to log4j?

This answer may be not related to the question asked but related to title of the question.

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable("Created at main()");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        try {
        } catch (IOException e) {


public static String getStackTrace (Throwable t)
    StringWriter stringWriter = new StringWriter();
    PrintWriter  printWriter  = new PrintWriter(stringWriter);
    printWriter.close();    //surprise no IO exception here
    try {
    catch (IOException e) {
    return stringWriter.toString();


StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
    logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());

Read text file into string array (and write)

Note: ioutil is deprecated as of Go 1.16.

If the file isn't too large, this can be done with the ioutil.ReadFile and strings.Split functions like so:

content, err := ioutil.ReadFile(filename)
if err != nil {
    //Do something
lines := strings.Split(string(content), "\n")

You can read the documentation on ioutil and strings packages.

git checkout tag, git pull fails in branch

First, make sure you are on the right branch.
Then (one time only):

git branch --track

After that this works again:

git pull

React Native android build failed. SDK location not found

Fixing SDK Path Errors on Linux Distributions

Your project is not finding the SDK set in the Project Settings via the path provided, so the project needs to be pointing in the right direction, and you have a couple options to accomplish this, but let's start by finding the correct SDK folder first.

Finding your SDK

From Package Manager

If you are using a package-based JRE install like Java 8 JRE via a the custom PPA in a Debian-based distribution, or used OpenJDK, the directory will most likely be /usr/lib/jvm/java-8-oracle (or whatever version you have chosen). You can find this path set in the JAVA_HOME environment variable:

$ echo $JAVA_HOME

Manual Download

If you have installed via the Java JRE/SDK download, it will be wherever you placed the folder, e.g. /home/username/jdk-8u121_1.8.0 (or something similar).

Scripted installs may even add the SDK to /opt/java-8-oracle, but as of this writing, the Java Install instructions leave the folder placement in your hands.

Android Studio 2.2

Lastly if you are using Android Studio, the SDK is placed where you have set it to place the SDK files downloaded through the Studio's SDK Manager. By going to File > Settings > Appearance & Behavior > System Settings > Android SDK, you can find the SDK location setting at the top with the option to change, and the default folder being ~/Android/Sdk.

Android Studio SDK Path

Setting the SDK Path

Now that we know where the SDK is, it is time to let react-native know.

Option 1: Set with

This method is very simple, and all that is needed is creating the file in the following folder, where Project_Folder is the base of your React-Native application:


In your, you want to set the variable sdk.dir to the path of your SDK folder:


While this is the easiest way to remedy the issue, it is not the best, especially if you work with multiple projects. For every project, you will have to create this file for every project, and if the folder changes plan on changing this file for each project's

Once the file is saved, rerun the react-native run-android command.

Option 2: Settings Folders with Environment Variables

The other option is to set the SDK folders to the local environment variables that React-Native looks for by default. To do so, we will add the ANDROID_HOME path. As a bonus we can also add our android tools in the same place. We need to add this to rather the .bash_profile or .profile files in our home directory, which are loaded last, so we can make sure that nothing else is overriding the settings we make. Since these are in your home directory, there is no need to edit with escalated privileges.

**$ vim ~/.profile**  (use nano or pico if you prefer)

In the file add the following lines replacing the SDK folder with the one you found above. I will be using the Android Studio folder as an example:

export ANDROID_HOME="~/Android/Sdk"
export PATH=$PATH:~/Android/Sdk/tools:~/Android/Sdk/platform-tools

Save the file, then apply the profile settings:

$ source ~/.profile

If the Sdk folder shows correctly, congratulations! Re-run your react-native command, and watch the app build process continue forward.

If you still have issues

If for some reason you receive the error "> failed to find target with hash string 'android-23' in: your/sdk/folder, you need to make sure that the project's build version and the version of the SDK installed match (React-Native defaults to 23.0.1). You can find the default version in Project_Folder/android/app/build.gradle, and then searching for buildToolsVersion. You can of course change the version from this file, or in Android Studio go to File > Project Structure to change the Project SDK. I would not suggest changing this version unless you absolutely know what you are doing, otherwise install the SDK version the project is looking for.

Cannot convert lambda expression to type 'string' because it is not a delegate type

I think you are missing using System.Linq; from this system class.

and also add using System.Data.Entity; to the code

What's the best way to test SQL Server connection programmatically?

Here is my version based on the @peterincumbria answer:

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);

I'm using Observable for polling health checking by interval and handling return value of the function. try-catch is not needed here because: enter image description here

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail

    return new FileInfo(thumbnailFileName);

What's the default password of mariadb on fedora?

Had the same issue after installing mysql mariadb 10.3. The password was not NULL so simply pressing ENTER didn't worked for me. So finally had to change the password. I followed instruction from here. In nutshell; stop the server

sudo systemctl stop mariadb.service

gain access to the server through a backdoor by starting the database server and skipping networking and permission tables.

sudo mysqld_safe --skip-grant-tables --skip-networking &

login as root

sudo mysql -u root

then change server password

use mysql;
update user set password=PASSWORD("new_password_here") where User='root';

Note that after MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'. So use appropriate table name based on mysql version. finally save changes & restart the server

flush privileges;
sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

PHP - iterate on string characters

Hmm... There's no need to complicate things. The basics work great always.

    $string = 'abcdef';
    $len = strlen( $string );
    $x = 0;

Forward Direction:

while ( $len > $x ) echo $string[ $x++ ];

Outputs: abcdef

Reverse Direction:

while ( $len ) echo $string[ --$len ];

Outputs: fedcba

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {

You will also need to have this in order to have webjars enabled:

    public class MvcConfig extends WebMvcConfigurerAdapter {
        public void addResourceHandlers(ResourceHandlerRegistry registry) {

Escaping a forward slash in a regular expression

Here are a few options:

  • In Perl, you can choose alternate delimiters. You're not confined to m//. You could choose another, such as m{}. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{} is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, // and {} seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...), m[...], and m!...!.

  • In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$}, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.

SimpleDateFormat and locale based format string

Hope this helps someone. Please find in the below code which accepts Locale instance and returns the locale specific date format/pattern.

public static String getLocaleDatePattern(Locale locale) {
    // Validating if Locale instance is null
    if (locale == null || locale.getLanguage() == null) {
        return "MM/dd/yyyy";
    // Fetching the locale specific date pattern
    String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
            DateFormat.SHORT, locale)).toPattern();
    // Validating if locale type is having language code for Chinese and country
    // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
    if (locale.toString().equalsIgnoreCase("zh_hk")) {
        // Expected application Date Format for Chinese (Hong Kong) locale type
        return "yyyy'MM'dd";
    // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
    localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd")
            .replaceAll("M{1,2}", "MM")
            .replaceAll("y{1,4}|Gy", "yyyy");
    // Replacing all blank spaces in the locale date pattern
    localeDatePattern = localeDatePattern.replace(" ", "");
    // Validating the date pattern length to remove any extract characters
    if (localeDatePattern.length() > 10) {
        // Keeping the standard length as expected by the application
        localeDatePattern = localeDatePattern.substring(0, 10);
    return localeDatePattern;

What is the Oracle equivalent of SQL Server's IsNull() function?

Instead of ISNULL(), use NVL().


SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable


SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable

Time complexity of Euclid's Algorithm

There's a great look at this on the wikipedia article.

It even has a nice plot of complexity for value pairs.

It is not O(a%b).

It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b). The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b) where b is the smaller number. That's an upper limit, and the actual time is usually less.

How to handle configuration in Go

Just use standard go flags with iniflags.

Standard go flags have the following benefits:

  • Idiomatic.
  • Easy to use. Flags can be easily added and scattered across arbitrary packages your project uses.
  • Flags have out-of-the-box support for default values and description.
  • Flags provide standard 'help' output with default values and description.

The only drawback standard go flags have - is management problems when the number of flags used in your app becomes too large.

Iniflags elegantly solves this problem: just modify two lines in your main package and it magically gains support for reading flag values from ini file. Flags from ini files can be overriden by passing new values in command-line.

See also!topic/golang-nuts/TByzyPgoAQE for details.

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen() after 'dynamic library').

They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.

Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.

HTML for the Pause symbol in audio and video control

I'm using ▐ ▌

HTML: &#9616;&nbsp;&#9612;

CSS: \2590\A0\258C

RuntimeWarning: DateTimeField received a naive datetime

One can both fix the warning and use the timezone specified in, which might be different from UTC.

For example in my I have:

USE_TZ = True
TIME_ZONE = 'Europe/Paris'

Here is a solution; the advantage is that str(mydate) gives the correct time:

>>> from datetime import datetime
>>> from django.utils.timezone import get_current_timezone
>>> mydate =
>>> mydate
datetime.datetime(2019, 3, 10, 11, 16, 9, 184106, 
    tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> str(mydate)
'2019-03-10 11:16:09.184106+01:00'

Another equivalent method is using make_aware, see dmrz post.

Checking during array iteration, if the current element is the last element

$myarray = array(
  'test1' => 'foo',
  'test2' => 'bar',
  'test3' => 'baz',
  'test4' => 'waldo'

$myarray2 = array(

// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";

// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";

Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.

$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz

how to install apk application from my pc to my mobile android

1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.

2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...

How to open .dll files to see what is written inside?

I use the Jetbrains Dot peek Software , you can try that too

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);

Advantages of SQL Server 2008 over SQL Server 2005?

Someone with more reputation can copy this into the main answer:

  • Change Tracking. Allows you to get info on what changes happened to which rows since a specific version.
  • Change Data Capture. Allows all changes to be captured and queried. (Enterprise)

Stopping a JavaScript function when a certain condition is met

Use a try...catch statement in your main function and whenever you want to stop the function just use:

throw new Error("Stopping the function!");

How set the android:gravity to TextView from Java side in Android

We can set layout gravity on any view like below way-

myView = findViewById(;

This is equilent to below xml code


How to add headers to OkHttp request interceptor?

If you are using Retrofit library then you can directly pass header to api request using @Header annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.

void methodName(
        @Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
        @Header(HeadersContract.HEADER_CLIENT_ID) String token,
        @Body TypedInput body,
        Callback<String> callback);

Hope it helps!

How to check if any Checkbox is checked in Angular

If you have only one checkbox, you can do this easily with just ng-model:

<input type="checkbox" ng-model="checked"/>
<button ng-disabled="!checked"> Next </button>

And initialize $scope.checked in your Controller (default=false). The official doc discourages the use of ng-init in that case.

Warning as error - How to get rid of these

In the Properties,

Go to Configuration Properties. In that go to C/C++ (or something like that). ,Then click General ,In that remove the check in the "Treat Warning As Errors" Check Box

How can I embed a YouTube video on GitHub wiki pages?

Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:

  • if the official video link is:
  • then the thumbnail is:

Following this logic, the code below produces flawless results:

<div align="left">
      <a href="">
         <img src="" style="width:100%;">

Scatter plots in Pandas/Pyplot: How to plot by category

seaborn has a wrapper function scatterplot that does it more efficiently.

sns.scatterplot(data = df, x = 'one', y = 'two', data =  'key1'])

Returning multiple values from a C++ function

Alternatives include arrays, generators, and inversion of control, but none is appropriate here.

Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.

"Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).

Get epoch for a specific date using Javascript

new Date("2016-3-17").valueOf() 

will return a long epoch

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() returns true for blanks(just whitespaces)and for null String as well. Actually it trims the Char sequences and then performs check.

StringUtils.isEmpty() returns true when there is no charsequence in the String parameter or when String parameter is null. Difference is that isEmpty() returns false if String parameter contains just whiltespaces. It considers whitespaces as a state of being non empty.

How to set an image as a background for Frame in Swing GUI of java?

Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components. enter image description here

    ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
    Image img=background.getImage();
    Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
    background=new ImageIcon(temp);
    JLabel back=new JLabel(background);

How to upload file using Selenium WebDriver in Java


Show loading gif after clicking form submit using jQuery

What about an onclick function:

    <form id="form">
    <input type="text" name="firstInput">
    <button type="button" name="namebutton" 
           onClick="$('#gif').css('visibility', 'visible');

Of course you can put this in a function and then trigger it with an onClick

Error while trying to retrieve text for error ORA-01019

I have the same issue. My solution was delete one of the oracle path in environment variable. I also changed the inventory.xml and point to the oracle home version which is in my environment path variable.

What causes the Broken Pipe Error?

It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"

The only other possibility is you have an extension doing it for you.

How to read pickle file?

The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.

import os
import pickle

PICKLE_FILE = 'pickle.dat'

def main():
    # append data to the pickle file
    add_to_pickle(PICKLE_FILE, 123)
    add_to_pickle(PICKLE_FILE, 'Hello')
    add_to_pickle(PICKLE_FILE, None)
    add_to_pickle(PICKLE_FILE, b'World')
    add_to_pickle(PICKLE_FILE, 456.789)
    # load & show all stored objects
    for item in read_from_pickle(PICKLE_FILE):

def add_to_pickle(path, item):
    with open(path, 'ab') as file:
        pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)

def read_from_pickle(path):
    with open(path, 'rb') as file:
            while True:
                yield pickle.load(file)
        except EOFError:

if __name__ == '__main__':

Add Facebook Share button to static HTML page

Replace <url> with your own link

<script>function fbs_click() {u=location.href;t=document.title;''+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_link { padding:2px 0 0 20px; height:16px; background:url( no-repeat top left; }</style><a rel="nofollow" href="<;url>" onclick="return fbs_click()" target="_blank" class="fb_share_link">Share on Facebook</a>

Display date in dd/mm/yyyy format in

Like this ..


How to compile a c++ program in Linux?

$ g++ 1st.cpp -o 1st

$ ./1st

if you found any error then first install g++ using code as below

$ sudo apt-get install g++

then install g++ and use above run code

how to remove the bold from a headline?

<h1><span>This is</span> a Headline</h1>

h1 { font-weight: normal; text-transform: uppercase; }
h1 span { font-weight: bold; }

I'm not sure if it was just for the sake of showing us, but as a side note, you should always set uppercase text with CSS :)

Can I specify maxlength in css?

As others have answered, there is no current way to add maxlength directly to a CSS class.

However, this creative solution can achieve what you are looking for.

I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)

run the snippet to see it in action, works well.

jquery, css, html:

$(function () {_x000D_
    $(".maxLenAddress1").keypress(function (event) {_x000D_
        if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */_x000D_
            return false;_x000D_
        } else {_x000D_
            return true;_x000D_
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
<script src=""></script>_x000D_
<input type="text" class="maxLenAddress1" />

The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.

Delete all records in a table of MYSQL in phpMyAdmin

'Truncate tableName' will fail on a table with key constraint defined. It will also not reindex the table AUTO_INCREMENT value. Instead, Delete all table entries and reset indexing back to 1 using this sql syntax:

DELETE FROM tableName;

How to redirect siteA to siteB with A or CNAME records

These days, many site owners are using CDN services which pulls data from CDN server. If that's your case then you are left with two options:

  1. Create a subdomain and edit DNS by Adding a CNAME record

  2. Don't create a subdomain but only create a CNAME record pointing back to your temporary DNS URL.

This solution only implies to pulling code from CDN which will show that it's fetching data from but practically its pulling from your CDN host.

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;

How to set data attributes in HTML elements

Please take note that jQuery .data() is not updated when you change html5 data- attributes with javascript.

If you use jQuery .data() to set data- attributes in HTML elements you better use jQuery .data() to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute(), dataset(), attr() below. Change the value, push the button several times and see the console.

$("#button").on("click", function() {_x000D_
  var field = document.querySelector("#textfield")_x000D_
  switch ($("#method").val()) {_x000D_
    case "setAttribute":_x000D_
      field.setAttribute("data-customval", field.value)_x000D_
    case "dataset":_x000D_
      field.dataset.customval = field.value_x000D_
    case "jQuerydata":_x000D_
      $(field).data("customval", field.value)_x000D_
    case "jQueryattr":_x000D_
      $(field).attr("data-customval", field.value)_x000D_
  objValues = {}_x000D_
  objValues['$(field).data("customval")'] = $(field).data("customval")_x000D_
  objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")_x000D_
  objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")_x000D_
  objValues['field.dataset.customval'] = field.dataset.customval_x000D_
<script src=""></script>_x000D_
  <input id="textfield" type="text" data-customval="initial">_x000D_
  <input type="button" value="Set and show in console.table (F12)" id="button">_x000D_
  <select id="method">_x000D_
    <option value="setAttribute">setAttribute</option>_x000D_
    <option value="dataset">dataset</option>_x000D_
    <option value="jQuerydata">jQuery data</option>_x000D_
    <option value="jQueryattr">jQuery attr</option>_x000D_
  <div id="results"></div>_x000D_

Use index in pandas to plot data

Try this,

monthly_mean.plot(y='A', use_index=True)

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

Java - escape string to prevent SQL injection

If you are using PL/SQL you can also use DBMS_ASSERT it can sanitize your input so you can use it without worrying about SQL injections.

see this answer for instance:

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

A general answer

select * from [dbo].[SplitString]('1,2',',') -- Will work 


select [dbo].[SplitString]('1,2',',')  -- will not work and throws this error

Bootstrap modal in React.js

Solution using React functional components.

import React, { useState, useRef, useEffect } from 'react'

const Modal = ({ title, show, onButtonClick }) => {

    const dialog = useRef({})

    useEffect(() => { $(dialog.current).modal(show ? 'show' : 'hide') }, [show])
    useEffect(() => { $(dialog.current).on('', () =>
        onButtonClick('close')) }, [])

    return (
        <div className="modal fade" ref={dialog}
            id="modalDialog" tabIndex="-1" role="dialog"
            aria-labelledby="modalDialogLabel" aria-hidden="true"
            <div className="modal-dialog" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title" id="modalDialogLabel">{title}</h5>
                        <button type="button" className="close" aria-label="Close"
                            onClick={() => onButtonClick('close')}
                            <span aria-hidden="true">&times;</span>
                    <div className="modal-body">
                    <div className="modal-footer">
                        <button type="button" className="btn btn-secondary"
                            onClick={() => onButtonClick('close')}>Close</button>
                        <button type="button" className="btn btn-primary"
                            onClick={() => onButtonClick('save')}>Save</button>

const App = () => {

    const [ showDialog, setShowDialog ] = useState(false)

    return (
        <div className="container">
                title="Modal Title"
                onButtonClick={button => {
                    if(button == 'close') setShowDialog(false)
                    if(button == 'save') console.log('save button clicked')
            <button className="btn btn-primary" onClick={() => {
            }}>Show Dialog</button>