Programs & Examples On #Firefox3.5

Version 3.5 of the Mozilla Firefox browser, which was released on 30 June 2009.

changing visibility using javascript

function loadpage (page_request, containerid)
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 ) = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
      document.getElementById(containerid).innerHTML=page_request.responseText ; = "hidden" ;

What are the differences between 'call-template' and 'apply-templates' in XSL?

xsl:apply-templates is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.

xsl:call-template on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.

So I use xsl:apply-templates if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be

<xsl:template match="foo">

whereas with xsl:call-template I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.


As an additional remark to your specific question text:

<xsl:call-template name="nodes"/> 

This calls a template which is named 'nodes':

    <xsl:template name="nodes">...</xsl:template>

This is a different semantic than:

<xsl:apply-templates select="nodes"/>

...which applies all templates to all children of your current XML node whose name is 'nodes'.

Bootstrap 3 - disable navbar collapse

Another way is to simply remove collapse navbar-collapse from the markup. Example with Bootstrap 3.3.7

<link href="" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<nav class="navbar navbar-atp">_x000D_
  <div class="container-fluid">_x000D_
    <div class="">_x000D_
      <ul class="nav navbar-nav nav-custom">_x000D_
          <a href="#" id="sidebar-btn"><span class="fa fa-bars">Toggle btn</span></a>_x000D_
      <ul class="nav navbar-nav navbar-right">_x000D_
        <li>Nav item</li>_x000D_

Moving up one directory in Python

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects:

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/")
>>> p.parent
>>> p.ext

How do you change the value inside of a textfield flutter?

step 1) Declare TextEditingController.

step 2) supply controller to the TextField.

step 3) user controller's text property to change the value of the textField.

follow this official solution to the problem

Non-static variable cannot be referenced from a static context

Let's analyze your program first.. In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.

Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing. *Static method calls only the static method and use only the static variable. *Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class) *Because of this you call it as a class variable or a class method. And a lot more is there about the "static" keyword. I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).

And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.

How to include NA in ifelse?

It sounds like you want the ifelse statement to interpret NA values as FALSE instead of NA in the comparison. I use the following functions to handle this situation so I don't have to continuously handle the NA situation:

falseifNA <- function(x){
  ifelse(, FALSE, x)

ifelse2 <- function(x, a, b){
  ifelse(falseifNA(x), a, b)

You could also combine these functions into one to be more efficient. So to return the result you want, you could use:

test$ID <- ifelse2($time) | test$type == "A", NA, "1")

Keyboard shortcuts are not active in Visual Studio with Resharper installed

First you need to reset VS setting (tools > option > Export Settings > Reset all settings) and click Resharper button(Option > Environment > Keyboard&Menu > Keyboard shortcuts) select item you want to use and apply scheme.

It's work for me on visual studio 2012.

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource:

Or use linq if you have objects in you datasource

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {

Restore a deleted file in the Visual Studio Code Recycle Bin

Running on Ubuntu 18.04, with VS code 1.51.0

My deleted files from VS Code are located at:


To search for your deleted files:

find ~/.local/share/Trash/files -name your_file_name 

Hope my case helped!

When should I really use noexcept?

In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):

Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§ Also, a noexcept specifier (§ can make that desire explicit.

Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore, terminate() supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly, noexcept provides a simple escape for errors where trying to recover seems infeasible.

double compute(double x) noexcept;     {
    string s = "Courtney and Anya";
    vector<double> tmp(10);
    // ...

The vector constructor may fail to acquire memory for its ten doubles and throw a std::bad_alloc. In that case, the program terminates. It terminates unconditionally by invoking std::terminate() (§ It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between the throw and the noexcept (e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding a noexcept specifier, we indicate that our code was not written to cope with a throw.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

public class AuthenticationController {
private AuthenticationManager authenticationManager;
//some logic

Spring doc about Aggregating @Configuration classes with @Import: link

Multiple inputs on one line

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:

cin >> a;
cin >> b;
cin >> c;

This is due to a technique called "operator chaining".

Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.

Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite:

How to resolve TypeError: can only concatenate str (not "int") to str

Use f-strings to resolve the TypeError

# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'

# same intent with a f-string
i = 15

test = f'Here is a test that can be run {i} times'


# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i  # will cause a TypeError

# should be
t = f'test{i}'


# output
  • The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
  • Convert the string to an int.
  • This scenario is specific to this question
  • When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i  # will cause a TypeError

# convert the string to int
t = 15 + int(i)

# output


  • The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
  • However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.

Original Code Issues

  • TypeError is caused because message type is a str.
  • The code iterates each character and attempts to add char, a str type, to an int
  • That issue can be resolved by converting char to an int
  • As the code is presented, secret_string needs to be initialized with 0 instead of "".
  • The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
  • Resolved by using a smaller number
  • The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")

secret_string = 0

for char in message:
    char = int(char)
    value = char + 742146
    secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')

# Output
Enter a message you want to be revealed:  999

Revealed: 2226465

Updated Code Issues

  • message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
  • message is converted to int to make sure the input is an int.
  • Set the type with str()
  • Only convert value to Unicode with chr
  • Don't use ord
while True:
        message = str(int(input("Enter a message you want to be decrypt: ")))
    except ValueError:
        print("Error, it must be an integer")
secret_string = ""
for char in message:
    value = int(char) + 10000
    secret_string += chr(value)

print("Decrypted", secret_string)

# output
Enter a message you want to be decrypt:  999
Decrypted ???

Enter a message you want to be decrypt:  100
Decrypted ???

Does bootstrap 4 have a built in horizontal divider?

Here are some custom utility classes:

hr.dashed {
    border-top: 2px dashed #999;

hr.dotted {
    border-top: 2px dotted #999;

hr.solid {
    border-top: 2px solid #999;
} {
  position: relative;
    border: none;
    height: 1px;
    background: #999;
} {
    content: attr(data-content);
    display: inline-block;
    background: #fff;
    font-weight: bold;
    font-size: 0.85rem;
    color: #999;
    border-radius: 30rem;
    padding: 0.2rem 2rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

* ==========================================
* ==========================================

body {
    min-height: 100vh;
    background-color: #fff; 
    color: #333;
.text-uppercase {
  letter-spacing: .1em;
<link rel="stylesheet" href="">

<div class="container py-5">
    <!-- For Demo Purpose -->
    <header class="py-5 text-center">
        <h1 class="display-4">Bootstrap Divider</h1>
        <p class="lead mb-0">Some divider variants using &lt;hr&gt; element.    </p>

    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="mb-4">
                <h6 class=" text-uppercase">Dashed</h6>
                <!-- Dashed divider -->
                <hr class="dashed">
            <div class="mb-4">
                <h6 class=" text-uppercase">Dotted</h6>
                <!-- Dotted divider -->
                <hr class="dotted">
            <div class="mb-4">
                <h6 class="text-uppercase">Solid</h6>
                <!-- Solid divider -->
                <hr class="solid">
            <div class="mb-4">
                <h6 class=" text-uppercase">Text content</h6>
                <!-- Gradient divider -->
                <hr data-content="AND" class="hr-text">

How to check type of files without extensions in python?

import subprocess
p = sub.Popen('file yourfile.txt', stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = p.communicate()

As Steven pointed out, subprocess is the way. You can get the command output by the way above as this post said

How to generate range of numbers from 0 to n in ES2015 only?

Here's another variation that doesn't use Array.

let range = (n, l=[], delta=1) => {
  if (n < 0) { 
    return l 
  else {
    return range(n - delta, l) 

Find out free space on tablespace

Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.

I think the code below does that. It calculates free space as "freespace" + unallocated space.

     reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
    (select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;

How to reset AUTO_INCREMENT in MySQL?

Here is my solution, but I will not advise to do this if your column has constraints or is connected as foreign key to other tables as it would have bad effects or will not even work.

> First : drop the column

ALTER TABLE tbl_name DROP COLUMN column_id

> Second : recreate the column and set it as FIRST if you want it as the first column I assume.


This works well!

Regex in JavaScript for validating decimal numbers

Numbers with at most 2 decimal places:


This should work fine. Please try out :)

Comparing two .jar files

If you select two files in IntellijIdea and press Ctrl + Dthen it will show you the diff. I use Ultimate and don't know if it will work with Community edition.

How do you remove columns from a data.frame?

Just addressing the edit.

@nzcoops, you do not need the column names in a comma delimited character vector. You are thinking about this the wrong way round. When you do

vec <- c("col1", "col2", "col3")

you are creating a character vector. The , just separates arguments taken by the c() function when you define that vector. names() and similar functions return a character vector of names.

> dat <- data.frame(col1 = 1:3, col2 = 1:3, col3 = 1:3)
> dat
  col1 col2 col3
1    1    1    1
2    2    2    2
3    3    3    3
> names(dat)
[1] "col1" "col2" "col3"

It is far easier and less error prone to select from the elements of names(dat) than to process its output to a comma separated string you can cut and paste from.

Say we want columns col1 and col2, subset names(dat), retaining only the ones we want:

> names(dat)[c(1,3)]
[1] "col1" "col3"
> dat[, names(dat)[c(1,3)]]
  col1 col3
1    1    1
2    2    2
3    3    3

You can kind of do what you want, but R will always print the vector the screen in quotes ":

> paste('"', names(dat), '"', sep = "", collapse = ", ")
[1] "\"col1\", \"col2\", \"col3\""
> paste("'", names(dat), "'", sep = "", collapse = ", ")
[1] "'col1', 'col2', 'col3'"

so the latter may be more useful. However, now you have to cut and past from that string. Far better to work with objects that return what you want and use standard subsetting routines to keep what you need.

How can I format a String number to have commas and round?

Here is the simplest way to get there:

String number = "10987655.876";
double result = Double.parseDouble(number);

output: 10,987,655.88

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a small module to do just that, called timexe:

  • Its simple,small reliable code and has no dependencies
  • Resolution is in milliseconds and has high precision over time
  • Cron like, but not compatible (reversed order and other Improvements)
  • I works in the browser too


npm install timexe


var timexe = require('timexe');
//Every 30 sec
var res1=timexe(”* * * * * /30”, function() console.log(“Its time again”)});

//Every minute
var res2=timexe(”* * * * *”,function() console.log(“a minute has passed”)});

//Every 7 days
var res3=timexe(”* y/7”,function() console.log(“its the 7th day”)});

//Every Wednesdays 
var res3=timexe(”* * w3”,function() console.log(“its Wednesdays”)});

// Stop "every 30 sec. timer"

you can achieve start/stop functionality by removing/re-adding the entry directly in the timexe job array. But its not an express function.

How can I sort an ArrayList of Strings in Java?

Take a look at the Collections.sort(List<T> list).

You can simply remove the first element, sort the list and then add it back again.

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

How to hide console window in python?

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :

    import win32gui, win32con;

    frgrnd_wndw = win32gui.GetForegroundWindow();
    wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
    if wndw_title.endswith("python.exe"):
        win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
except  :

Firefox 'Cross-Origin Request Blocked' despite headers

Turns out this has nothing to do with CORS- it was a problem with the security certificate. Misleading errors = 4 hours of headaches.

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

Async always WaitingForActivation

For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task class and TaskStatus enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.

In the context of methods marked as async, the resulting Task is not a Task representing the execution of the method, but a Task for the continuation of the method.

This is only able to make use of a few possible states:

  • Canceled
  • Faulted
  • RanToCompletion
  • WaitingForActivation

I understand that Runningcould appear to have been a better default than WaitingForActivation, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await-ing something else). The other option may have been to add a new value to TaskStatus, however this could have been a breaking change for existing applications and libraries.

All of this is very different to when making use of Task.Run which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus enumeration.

If you wish to keep track of the status of an async method, take a look at the IProgress(T) interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T) interface.

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

Check if the number is integer

For a vector m, m[round(m) != m] will return the indices of values in the vector that are not integers.

Two div blocks on same line

Use Simple HTML

<frameset cols="25%,*">
  <frame src="frame_a.htm">
  <frame src="frame_b.htm">

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Java Scanner class reading strings

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(;
nnames = in.nextInt();

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();

or just read the line and parse the value as an Integer.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(;
nnames = Integer.parseInt(in.nextLine().trim());

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This helped me out after reading @Mr-Faizan's and other answers.

Untick the 'Enable foreign key checks'

in phpMyAdmin and hit the query. I don't know about WorkBench but the other answers might help you out.

SSH to Elastic Beanstalk instance

Elastic beanstalk CLI v3 now supports direct SSH with the command eb ssh. E.g.

eb ssh your-environment-name

No need for all the hassle of setting up security groups of finding out the EC2 instance address.

There's also this cool trick:

eb ssh --force

That'll temporarily force port 22 open to, and keep it open until you exit. This blends a bit of the benefits of the top answer, without the hassle. You can temporarily grant someone other than you access for debugging and whatnot. Of course you'll still need to upload their public key to the host for them to have access. Once you do that (and as long as you're inside eb ssh), the other person can

ssh [email protected]

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.


$response = $client->post('', [
    'body' => [
        'name' => 'Example name',


$response = $client->post('', [
    'json' => [
        'name' => 'Example name',


$response = $client->post('', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',

ImportError: No module named scipy

if you are using pycharm go to settings and in project interpreter sub-tab click on "+" sign next to list and in the search bar in there search name "scipy" and install the package.


angularjs: allows only numbers to be typed into a text box

Use ng-only-number to allow only numbers, for example:

<input type="text" ng-only-number data-max-length=5>

What Java ORM do you prefer, and why?

Eclipse Link, for many reasons, but notably I feel like it has less bloat than other main stream solutions (at least less in-your-face bloat).

Oh and Eclipse Link has been chosen to be the reference implementation for JPA 2.0

Android map v2 zoom to show all the markers

I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.

 public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
    float max = 0;

    if (l == null || l.length == 0) {
        return null;
    LatLngBounds.Builder b = new LatLngBounds.Builder();
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {

    LatLng center =;

    float distance = 0;
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {
        distance = distance(center, l[count]);
        if (distance > max) {
            max = distance;

    double scale = max / 1000;
    int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
    return new Pair<LatLng, Integer>(center, zoom);

This function return Pair object which you can use like

Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));

you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.

Drop shadow on a div container?

The most widely compatible way of doing this is likely going to be creating a second div under your auto-suggest box the same size as the box itself, nudged a few pixels down and to the right. You can use JS to create and position it, which shouldn't be terribly difficult if you're using a fairly modern framework.

Angular 2 / 4 / 5 - Set base href dynamically

In angular4, you can also configure the baseHref in .angular-cli.json apps.

in .angular-cli.json

{   ....
 "apps": [
            "name": "myapp1"
            "baseHref" : "MY_APP_BASE_HREF_1"
            "name": "myapp2"
            "baseHref" : "MY_APP_BASE_HREF_2"

this will update base href in index.html to MY_APP_BASE_HREF_1

ng build --app myapp1

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;


@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

Angular 4.3 - HttpClient set params

Since @MaciejTreder confirmed that we have to loop, here's a wrapper that will optionally let you add to a set of default params:

function genParams(params: object, httpParams = new HttpParams()): object {
        .filter(key => {
            let v = params[key];
            return (Array.isArray(v) || typeof v === 'string') ? 
                (v.length > 0) : 
                (v !== null && v !== undefined);
        .forEach(key => {
            httpParams = httpParams.set(key, params[key]);
    return { params: httpParams };

You can use it like so:

const OPTIONS = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
    params: new HttpParams().set('verbose', 'true')
let opts = Object.assign({}, OPTIONS, genParams({ id: 1 }, OPTIONS.params));
this.http.get(BASE_URL, opts); // --> ...?verbose=true&id=1

Factorial using Recursion in Java

A recursive solution using ternary operators.

public static int fac(int n) {
    return (n < 1) ? 1 : n*fac(n-1);

no target device found android studio 2.1.1

  1. Set up a device for development

  2. Enable developer options and debugging


  1. How to enable Developer options and USB debugging
    • Open Settings menu on Home screen.
    • Scroll to About Tablet and tap it.
    • Click on Build number for seven times until a pop-up message says “You are now a developer!”

file_get_contents() how to fix error "Failed to open stream", "No such file"

I just solve this by encode params in the url.
URL may be: http://abc/dgdc.php?p1=Hello&p2=some words
we just need to encode the params2.

$params2 = "some words";
$params2 = urlencode($params2);

$url = "http://abc/dgdc.php?p1=djkl&p2=$params2"

$result = file_get_contents($url);

How to read and write to a text file in C++?

To read you should create an instance of ifsteam and not ofstream.

ifstream iusrfile;

You should open the file in read mode."usrfile.txt", ifstream::in);

Also this statement is not correct.


If you are trying to print the data you read from the file you should do:


You can read more about ifstream and its API here

Angular 2 two way binding using ngModel is not working

The answer that helped me: The directive [(ngModel)]= not working anymore in rc5

To sum it up: input fields now require property name in the form.

How to sort an array of ints using a custom comparator?

If you don't want to copy the array (say it is very large), you might want to create a wrapper List<Integer> that can be used in a sort:

final int[] elements = {1, 2, 3, 4};
List<Integer> wrapper = new AbstractList<Integer>() {

        public Integer get(int index) {
            return elements[index];

        public int size() {
            return elements.length;

        public Integer set(int index, Integer element) {
            int v = elements[index];
            elements[index] = element;
            return v;


And now you can do a sort on this wrapper List using a custom comparator.

Sort an ArrayList based on an object field

Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
     return(degree -;

then just use


How to move screen without moving cursor in Vim?

my mnemonic for scrolling...

Adding to other answers also pay attention to ze and zs, meaning: move screen to the left/right of the cursor (without moving the cursor)

^                               |
|c-e (keep cursor)              |
|H(igh)             zt (top)    |
|                   ^           |
|           ze      |      zs   |
|M(iddle)  zh/zH <--zz--> zl/zL |
|                   |           |
|                   v           |
|L(ow)              zb (bottom) |
|c-y (keep cursor)              |
v                               |

also look at the position of h and l and t and b and (with qwertz keyboard) c-e and c-y (also the "y" somehow points to the bottom) on the keyboard to remember where the screen is moving.

How to delete a file after checking whether it exists

Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.

public static void DeleteFile(string path)
            if (!File.Exists(path))

            bool isDeleted = false;
            while (!isDeleted)
                    isDeleted = true;
                catch (Exception e)

Note:An exception is not thrown if the specified file does not exist.

Clone private git repo with dockerfile

For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.

bitbucket user menu

Then the command that you should use is:

git clone https://username:[email protected]/reponame/projectname.git

iPhone keyboard, Done button and resignFirstResponder

One line code for Done button:-

[yourTextField setReturnKeyType:UIReturnKeyDone];

And add action method on valueChanged of TextField and add this line-

[yourTextField resignFirstResponder];

Why is __init__() always called after __new__()?

In most well-known OO languages, an expression like SomeClass(arg1, arg2) will allocate a new instance, initialise the instance's attributes, and then return it.

In most well-known OO languages, the "initialise the instance's attributes" part can be customised for each class by defining a constructor, which is basically just a block of code that operates on the new instance (using the arguments provided to the constructor expression) to set up whatever initial conditions are desired. In Python, this corresponds to the class' __init__ method.

Python's __new__ is nothing more and nothing less than similar per-class customisation of the "allocate a new instance" part. This of course allows you to do unusual things such as returning an existing instance rather than allocating a new one. So in Python, we shouldn't really think of this part as necessarily involving allocation; all that we require is that __new__ comes up with a suitable instance from somewhere.

But it's still only half of the job, and there's no way for the Python system to know that sometimes you want to run the other half of the job (__init__) afterwards and sometimes you don't. If you want that behavior, you have to say so explicitly.

Often, you can refactor so you only need __new__, or so you don't need __new__, or so that __init__ behaves differently on an already-initialised object. But if you really want to, Python does actually allow you to redefine "the job", so that SomeClass(arg1, arg2) doesn't necessarily call __new__ followed by __init__. To do this, you need to create a metaclass, and define its __call__ method.

A metaclass is just the class of a class. And a class' __call__ method controls what happens when you call instances of the class. So a metaclass' __call__ method controls what happens when you call a class; i.e. it allows you to redefine the instance-creation mechanism from start to finish. This is the level at which you can most elegantly implement a completely non-standard instance creation process such as the singleton pattern. In fact, with less than 10 lines of code you can implement a Singleton metaclass that then doesn't even require you to futz with __new__ at all, and can turn any otherwise-normal class into a singleton by simply adding __metaclass__ = Singleton!

class Singleton(type):
    def __init__(self, *args, **kwargs):
        super(Singleton, self).__init__(*args, **kwargs)
        self.__instance = None
    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super(Singleton, self).__call__(*args, **kwargs)
        return self.__instance

However this is probably deeper magic than is really warranted for this situation!

pip install gives error: Unable to find vcvarsall.bat

If you are trying to install matplotlib in order to work with graphs on python. Try this link. This is a set of scripts to build matplotlib from source on the MS Windows platform.

To build & install matplotlib in your Python, do:

git clone
git clone
$ python matplotlib-winbuild\

The build script will auto-detect Python version & 32/64 bit automatically.

How to get the Facebook user id using the access token

The facebook acess token looks similar too "1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc"

if you extract the middle part by using | to split you get


then split again by -

the last part 605430316 is the user id.

Here is the C# code to extract the user id from the access token:

   public long ParseUserIdFromAccessToken(string accessToken)

         * access_token:
         *   1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
         *                                               |_______|
         *                                                   |
         *                                                user id

        long userId = 0;

        var accessTokenParts = accessToken.Split('|');

        if (accessTokenParts.Length == 3)
            var idPart = accessTokenParts[1];
            if (!string.IsNullOrEmpty(idPart))
                var index = idPart.LastIndexOf('-');
                if (index >= 0)
                    string id = idPart.Substring(index + 1);
                    if (!string.IsNullOrEmpty(id))
                        return id;

        return null;

WARNING: The structure of the access token is undocumented and may not always fit the pattern above. Use it at your own risk.

Update Due to changes in Facebook. the preferred method to get userid from the encrypted access token is as follows:

    var fb = new FacebookClient(accessToken);
    var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
    return (string)result["id"];
catch (FacebookOAuthException)
    return null;

How to set default value for HTML select?

Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

   <option selected="selected">a</option>

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I got a similar problem , I parsed the youtube url. The code is;

$json_is = "".$this->video_url."&max-results=1&alt=json";
$video_info = json_decode ( file_get_contents ( $json_is ), true );     
$video_title = is_array ( $video_info ) ? $video_info ['feed'] ['entry'] [0] ['title'] ['$t'] : '';

Then I realise that $this->video_url include the whitespace. I solved that using trim($this->video_url).

Maybe it will help you . Good Luck

Disable scrolling in webview?

Here is my code for disabling all scrolling in webview:

  // disable scroll on touch
  webview.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);

To only hide the scrollbars, but not disable scrolling:


or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:

   //Only disabled the horizontal scrolling:

You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:

android:scrollbars="vertical"    >
    android:scrollbars="none" />

And set


Don't forget to add the webview.setOnTouchListener(...) code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.

Node.js quick file server (static files over HTTP)

In plain node.js:

const http = require('http')
const fs = require('fs')
const path = require('path')

process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))

const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080

const mediaTypes = {
  zip: 'application/zip',
  jpg: 'image/jpeg',
  html: 'text/html',
  /* add more media types */

const server = http.createServer(function(request, response) {
  console.log(request.method + ' ' + request.url)

  const filepath = path.join(publicFolder, request.url)
  fs.readFile(filepath, function(err, data) {
    if (err) {
      response.statusCode = 404
      return response.end('File not found or you made an invalid request.')

    let mediaType = 'text/html'
    const ext = path.extname(filepath)
    if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
      mediaType = mediaTypes[ext.slice(1)]

    response.setHeader('Content-Type', mediaType)

server.on('clientError', function onClientError(err, socket) {
  console.log('clientError', err)
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')

server.listen(port, '', function() {
  console.log('? Development server is online.')

This is a simple node.js server that only serves requested files in a certain directory.


node server.js folder port

folder may be absolute or relative depending on the server.js location. The default value is . which is the directory you execute node server.js command.

port is 8080 by default but you can specify any port available in your OS.

In your case, I would do:

cd D:\Folder
node server.js

You can browse the files under D:\Folder from a browser by typing

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.


Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Invalid URI: The format of the URI could not be determined

I worked around this by using UriBuilder instead.

UriBuilder builder = new UriBuilder(slct.Text);

if (DeleteFileOnServer(builder.Uri))

How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

Passing functions with arguments to another function in Python?

(months later) a tiny real example where lambda is useful, partial not:
say you want various 1-dimensional cross-sections through a 2-dimensional function, like slices through a row of hills.
quadf( x, f ) takes a 1-d f and calls it for various x.
To call it for vertical cuts at y = -1 0 1 and horizontal cuts at x = -1 0 1,

fx1 = quadf( x, lambda x: f( x, 1 ))
fx0 = quadf( x, lambda x: f( x, 0 ))
fx_1 = quadf( x, lambda x: f( x, -1 ))
fxy = parabola( y, fx_1, fx0, fx1 )

f_1y = quadf( y, lambda y: f( -1, y ))
f0y = quadf( y, lambda y: f( 0, y ))
f1y = quadf( y, lambda y: f( 1, y ))
fyx = parabola( x, f_1y, f0y, f1y )

As far as I know, partial can't do this --

quadf( y, partial( f, x=1 ))
TypeError: f() got multiple values for keyword argument 'x'

(How to add tags numpy, partial, lambda to this ?)

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.


Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

The appearance of the scroll bars can be controlled with WebKit's -webkit-scrollbar pseudo-elements [blog]. You can disable the default appearance and behaviour by setting -webkit-appearance [docs] to none.

Because you're removing the default style, you'll also need to specify the style yourself or the scroll bar will never show up. The following CSS recreates the appearance of the hiding scroll bars:

Example (jsfiddle)

.frame::-webkit-scrollbar {
    -webkit-appearance: none;

.frame::-webkit-scrollbar:vertical {
    width: 11px;

.frame::-webkit-scrollbar:horizontal {
    height: 11px;

.frame::-webkit-scrollbar-thumb {
    border-radius: 8px;
    border: 2px solid white; /* should match background, can't be transparent */
    background-color: rgba(0, 0, 0, .5);

.frame::-webkit-scrollbar-track { 
    background-color: #fff; 
    border-radius: 8px; 
WebKit (Chrome) Screenshot

screenshot showing webkit's scrollbar, without needing to hover

Update query PHP MySQL

First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.

How to use timeit module

I find the easiest way to use timeit is from the command line:


def InsertionSort(): ...
def TimSort(): ...

run timeit like this:

% python -mtimeit -s'import test' 'test.InsertionSort()'
% python -mtimeit -s'import test' 'test.TimSort()'

How do I use $rootScope in Angular to store variables?

Variables set at the root-scope are available to the controller scope via prototypical inheritance.

Here is a modified version of @Nitish's demo that shows the relationship a bit clearer:

Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change function). Also, the rootScope's value can be updated too (the changeRs function in myCtrl2)

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();

    $scope.getOrig = function() {
        return $rootScope.test;
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();

    $scope.changeRs = function() {
        $rootScope.test = new Date();

    $scope.getOrig = function() {
        return $rootScope.test;

Background thread with QThread in PyQt

In PyQt there are a lot of options for getting asynchronous behavior. For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread. But for the vast majority of your threading needs, I think this solution is far superior than the other methods.

The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks. This is similar to the task pattern used in Intel's TBB. It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.

This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots. I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.

import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

def async(method, args, uid, readycb, errorcb=None):
    Asynchronously runs a task

    :param func method: the method to run in a thread
    :param object uid: a unique identifier for this task (used for verification)
    :param slot updatecb: the callback when data is receieved cb(uid, data)
    :param slot errorcb: the callback when there is an error cb(uid, errmsg)

    The uid option is useful when the calling code makes multiple async calls
    and the callbacks need some context about what was sent to the async method.
    For example, if you use this method to thread a long running database call
    and the user decides they want to cancel it and start a different one, the
    first one may complete before you have a chance to cancel the task.  In that
    case, the "readycb" will be called with the cancelled task's data.  The uid
    can be used to differentiate those two calls (ie. using the sql query).

    :returns: Request instance
    request = Request(method, args, uid, readycb, errorcb)
    return request

class Request(QtCore.QRunnable):
    A Qt object that represents an asynchronous task

    :param func method: the method to call
    :param list args: list of arguments to pass to method
    :param object uid: a unique identifier (used for verification)
    :param slot readycb: the callback used when data is receieved
    :param slot errorcb: the callback used when there is an error

    The uid param is sent to your error and update callbacks as the
    first argument. It's there to verify the data you're returning

    After created it should be used by invoking:

    .. code-block:: python

       task = Request(...)

    INSTANCES = []
    FINISHED = []
    def __init__(self, method, args, uid, readycb, errorcb=None):
        super(Request, self).__init__()
        self.cancelled = False

        self.method = method
        self.args = args
        self.uid = uid
        self.dataReady = readycb
        self.dataError = errorcb


        # release all of the finished tasks
        Request.FINISHED = []

    def run(self):
        Method automatically called by Qt when the runnable is ready to run.
        This will run in a separate thread.
        # this allows us to "cancel" queued tasks if needed, should be done
        # on shutdown to prevent the app from hanging
        if self.cancelled:

        # runs in a separate thread, for proper async signal/slot behavior
        # the object that emits the signals must be created in this thread.
        # Its not possible to run grabber.moveToThread(QThread.currentThread())
        # so to get this QObject to properly exhibit asynchronous
        # signal and slot behavior it needs to live in the thread that
        # we're running in, creating the object from within this thread
        # is an easy way to do that.
        grabber = Requester()
        grabber.Loaded.connect(self.dataReady, Qt.QueuedConnection)
        if self.dataError is not None:
            grabber.Error.connect(self.dataError, Qt.QueuedConnection)

            result = self.method(*self.args)
            if self.cancelled:
                # cleanup happens in 'finally' statement
            grabber.Loaded.emit(self.uid, result)
        except Exception as error:
            if self.cancelled:
                # cleanup happens in 'finally' statement
            grabber.Error.emit(self.uid, unicode(error))
            # this will run even if one of the above return statements
            # is executed inside of the try/except statement see:

    def cleanup(self, grabber=None):
        # remove references to any object or method for proper ref counting
        self.method = None
        self.args = None
        self.uid = None
        self.dataReady = None
        self.dataError = None

        if grabber is not None:

        # make sure this python obj gets cleaned up

    def remove(self):

            # when the next request is created, it will clean this one up
            # this will help us avoid this object being cleaned up
            # when it's still being used
        except ValueError:
            # there might be a race condition on shutdown, when shutdown()
            # is called while the thread is still running and the instance
            # has already been removed from the list

    def shutdown():
        for inst in Request.INSTANCES:
            inst.cancelled = True
        Request.INSTANCES = []
        Request.FINISHED = []

class Requester(QtCore.QObject):
    A simple object designed to be used in a separate thread to allow
    for asynchronous data fetching

    # Signals

    Error = QtCore.pyqtSignal(object, unicode)
    Emitted if the fetch fails for any reason

    :param unicode uid: an id to identify this request
    :param unicode error: the error message

    Loaded = QtCore.pyqtSignal(object, object)
    Emitted whenever data comes back successfully

    :param unicode uid: an id to identify this request
    :param list data: the json list returned from the GET

    NetworkConnectionError = QtCore.pyqtSignal(unicode)
    Emitted when the task fails due to a network connection error

    :param unicode message: network connection error message

    def __init__(self, parent=None):
        super(Requester, self).__init__(parent)

class ExampleObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(ExampleObject, self).__init__(parent)
        self.uid = 0
        self.request = None

    def ready_callback(self, uid, result):
        if uid != self.uid:
        print "Data ready from %s: %s" % (uid, result)

    def error_callback(self, uid, error):
        if uid != self.uid:
        print "Data error from %s: %s" % (uid, error)

    def fetch(self):
        if self.request is not None:
            # cancel any pending requests
            self.request.cancelled = True
            self.request = None

        self.uid += 1
        self.request = async(slow_method, ["arg1", "arg2"], self.uid,

def slow_method(arg1, arg2):
    print "Starting slow method"
    return arg1 + arg2

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)

    obj = ExampleObject()

    dialog = QtGui.QDialog()
    layout = QtGui.QVBoxLayout(dialog)
    button = QtGui.QPushButton("Generate", dialog)
    progress = QtGui.QProgressBar(dialog)
    progress.setRange(0, 0)

    app.deleteLater() # avoids some QThread messages in the shell on exit
    # cancel all running tasks avoid QThread/QTimer error messages
    # on exit

When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completed

Modify SVG fill color when being served as Background-Image

One way to do this is to serve your svg from some server side mechanism. Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.

Then you just use that url in your css.

Because as a background img, it isn't part of the DOM and you can't manipulate it. Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.

Excel formula to search if all cells in a range read "True", if not, then show "False"

As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF or SUMPRODUCT


ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

How to determine equality for two JavaScript objects?

Here is a very basic approach to checking an object's "value equality".

var john = {
    occupation: "Web Developer",
    age: 25

var bobby = {
    occupation: "Web Developer",
    age: 25

function isEquivalent(a, b) {
    // Create arrays of property names

    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // If number of properties is different, objects are not equivalent

    if (aProps.length != bProps.length) {
        return false;

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        // If values of same property are not equal, objects are not equivalent
        if (a[propName] !== b[propName]) {
           return false;

    // If we made it this far, objects are considered equivalent
    return true;

// Outputs: true
console.log(isEquivalent(john, bobby));

Demo - JSFiddle

As you can see, to check the objects' "value equality" we essentially have to iterate over every property in the objects to see whether they are equal. And while this simple implementation works for our example, there are a lot of cases that it doesn't handle. For instance:

  • What if one of the property values is itself an object?
  • What if one of the property values is NaN (the only value in JavaScript that is not equal to itself?)
  • What if a has a property with value undefined, while b doesn't have this property (which thus evaluates to undefined?)

For a robust method of checking objects' "value equality" it is better to rely on a well-tested library that covers the various edge cases like Underscore.

var john = {
    occupation: "Web Developer",
    age: 25

var bobby = {
    occupation: "Web Developer",
    age: 25

// Outputs: true
console.log(_.isEqual(john, bobby));

Demo - JSFiddle

Getting unique items from a list

Use a HashSet<T>. For example:

var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)



How can one pull the (private) data of one's own Android app?

Does that mean that one could chmod the directory from world:--x to world:r-x long enough to be able to fetch the files?

Yes, exactly. Weirdly enough, you also need the file to have the x bit set. (at least on Android 2.3)

chmod 755 all the way down worked to copy a file (but you should revert permissions afterwards, if you plan to continue using the device).

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
                foreach (T data in Record)
        catch (Exception ex)
            //Log exception here

        return objectOut;

call to process

        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);

or this call to process

        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();

Convert base class to derived class

No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.

Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.

Is it safe to store a JWT in localStorage with ReactJS?

Localstorage is designed to be accessible by javascript, so it doesn't provide any XSS protection. As mentioned in other answers, there is a bunch of possible ways to do an XSS attack, from which localstorage is not protected by default.

However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.

So cookies are a more secure choice for storing authentication data.

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

'uint32_t' does not name a type

if it happened when you include opencv header.

I would recommand that change the order of headers.

put the opencv headers just below the standard C++ header.

like this:


Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I am adding two sollution that work for me.

1st sollution is:

  1. Open database.php file insde config dir/folder.
  2. Edit 'engine' => null, to 'engine' => 'InnoDB',

    This worked for me.

2nd sollution is:

  1. Open database.php file insde config dir/folder.
    'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci',

    'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',


Does C# have a String Tokenizer like Java's?

I think the nearest in the .NET Framework is


parse html string with jquery

One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.

In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.

Get public/external IP address?

I find most of the other answers lacking as they assume that any returned string must be the IP, but doesn't really check for it. This is my solution that I'm currently using. It will only return a valid IP or null if none is found.

public class WhatsMyIp
    public static IPAddress PublicIp { get; private set; }
    static WhatsMyIp()
        PublicIp = GetMyIp();

    public static IPAddress GetMyIp()
        List<string> services = new List<string>()
        using (var webclient = new WebClient())
            foreach (var service in services)
                try { return IPAddress.Parse(webclient.DownloadString(service)); } catch { }
        return null;

How to calculate a time difference in C++

I would seriously consider the use of Boost, particularly boost::posix_time::ptime and boost::posix_time::time_duration (at

It's cross-platform, easy to use, and in my experience provides the highest level of time resolution an operating system provides. Possibly also very important; it provides some very nice IO operators.

To use it to calculate the difference in program execution (to microseconds; probably overkill), it would look something like this [browser written, not tested]:

ptime time_start(microsec_clock::local_time());
//... execution goes here ...
ptime time_end(microsec_clock::local_time());
time_duration duration(time_end - time_start);
cout << duration << '\n';

How to create an integer array in Python?

import numpy as np


An alternative for casting the type when the array is made.

SQL Server check case-sensitivity?

SQL server determines case sensitivity by COLLATION.

COLLATION can be set at various levels.

  1. Server-level
  2. Database-level
  3. Column-level
  4. Expression-level

Here is the MSDN reference.

One can check the COLLATION at each level as mentioned in Raj More's answer.

Check Server Collation


Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
where table_name = @table_name

Check Expression Collation

For expression level COLLATION you need to look at the expression. :)

It would be generally at the end of the expression as in below example.

SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;

Collation Description

For getting description of each COLLATION value try this.

SELECT * FROM fn_helpcollations()

And you should see something like this.

enter image description here

You can always put a WHERE clause to filter and see description only for your COLLATION.

You can find a list of collations here.

make arrayList.toArray() return more specific types

Like this:

List<String> list = new ArrayList<String>();

String[] a = list.toArray(new String[0]);

Before Java6 it was recommended to write:

String[] a = list.toArray(new String[list.size()]);

because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:


My example:


<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>


function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");

Here is a jsFiddle demo.

How to send a POST request from node.js Express?

in your server side the code looks like:

var request = require('request');'/add', function(req, res){
    json: {
    headers: {
        'Content-Type': 'application/json'
  function(error, response, body){
    // console.log(error);
    // console.log(response);
  // res.send("body");

in receiving end server code looks like:'/add', function(req, res){
console.log('received request')
let adunit = new AdUnit(req.body);
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
.catch(err => {
res.status(400).send('unable to save to database');

Schema is just two properties unit_name and unit_price.

How do I concatenate two strings in Java?

You must be a PHP programmer.

Use a + sign.

System.out.println("Your number is " + theNumber + "!");

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04

[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

Refresh or force redraw the fragment

I am using remove and replace both for refreshing content of Fragment like

final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

How do I get a list of folders and sub folders without the files?

dir /ad /b /s will give the required answer.

Check if string begins with something?

Have a look at JavaScript substring() method.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

run the below command in command prompt

tnsping Datasource

This should give a response like below

C:>tnsping *******

TNS Ping Utility for *** Windows: Version *** - Production on *****

Copyright (c) 1997, 2014, Oracle. All rights reserved.

Used parameter files: c:\oracle*****

Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)

Add the text 'Datasource=' in beginning and credentials at the end. the final string should be

Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**

Use this as the connection string to connect to oracle db.

Update Item to Revision vs Revert to Revision

@BaltoStar update to revision syntax:

svn update -r30

Where 30 is revision number. Hope this help!

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

            new Background(
                    Collections.singletonList(new BackgroundFill(
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),


                new Background(
                        Collections.singletonList(new BackgroundFill(
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                new BackgroundSize(1.0, 1.0, true, true, false, false)

(different last argument) to make the image full-window size.

Show DialogFragment with animation growing from a point

Check it out this code, it works for me

// Slide up animation

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="" >

        android:toXDelta="0" />


// Slide dowm animation

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="" >

        android:toYDelta="100%p" />


// Style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>

// Inside Dialog Fragment

public void onActivityCreated(Bundle arg0) {
    .getAttributes().windowAnimations =;

Dynamically converting java object of Object class to a given class when class name is known

you don't, declare an interface that declares the methods you would like to call:

public interface MyInterface
  void doStuff();

public class MyClass implements MyInterface
  public void doStuff()

then you use

MyInterface mobj = (myInterface)obj;

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).

How can I get browser to prompt to save password?

I found a fairly elegant solution (or hack, whatever fits) for Prototype.JS users, being one of the last holdouts using Prototype. A simple substitution of corresponding jQuery methods should do the trick.

First, make sure there's a <form> tag, and a submit button with a class name that can be referenced later (in this case faux-submit) that is nested inside an element with a style set to display:none, as illustrated below:

<form id="login_form" action="somewhere.php" method="post">
    <input type="text" name="login" />
    <input type="password" name="password" />
    <div style="display:none">
        <input class="faux-submit" type="submit" value="Submit" />
    <button id="submit_button">Login</button>

Then create a click observer for the button, that will "submit" the form as illustrated:

$('submit_button').observe('click', function(event) {

Then create a listener for submit event, and stop it. event.stop() will stop all submit events in the DOM unless it's wrapped in Event.findElement with the class of the hidden input button (as above, faux-submit):

document.observe('submit', function(event) {
    if (event.findElement(".faux-submit")) { 

This is tested as working in Firefox 43 and Chrome 50.

How to check whether a int is not null or empty?

I think you are asking about code like this.

int  count = (request.getParameter("counter") == null) ? 0 : Integer.parseInt(request.getParameter("counter"));

How to check if a Docker image with a specific tag exist locally?

Just a bit from me to very good readers:


#!/bin/bash -e
docker build -t smpp-gateway smpp
(if  [ $(docker ps -a | grep smpp-gateway | cut -d " " -f1) ]; then \
  echo $(docker rm -f smpp-gateway); \
else \
  echo OK; \
docker run --restart always -d --network="host" --name smpp-gateway smpp-gateway:latest


docker logs --tail 50 --follow --timestamps smpp-gateway


sudo docker exec -it \
$(sudo docker ps | grep "smpp-gateway:latest" | cut -d " " -f1) \

How to get the first column of a pandas DataFrame as a Series?


where i is the position/number of the column(starting from 0).

So, i = 0 is for the first column.

You can also get the last column using i = -1

Variables as commands in bash scripts

eval is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:

If you need to build up your commands over time, use arrays:

tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"

Alternately, if this is just about defining your commands in one central place, use functions:

tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd

How to avoid Python/Pandas creating an index in a saved csv?

If you want a good format the next statement is the best:

dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)

In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.

Changing image on hover with CSS/HTML

One solution is to use also the first image as a background image like this:

<div id="Library"></div>
#Library {
   background-image: url('LibraryTransparent.png');
   height: 70px;
   width: 120px;

#Library:hover {
   background-image: url('LibraryHoverTrans.png');

If your hover image has a different size, you've got to set them like so:

#Library:hover {
   background-image: url('LibraryHoverTrans.png');
   width: [IMAGE_WIDTH_IN_PIXELS]px;
   height: [IMAGE_HEIGHT_IN_PIXELS]px;

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Basically the error was because I was using old version of aws-sdk and I updated the version so this error occured.

in my case with node js i was using signatureVersion in parmas object like this :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    signatureVersion: 'v4',
    region: process.env.AWS_S3_REGION

Then I put signature out of params object and worked like charm :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    region: process.env.AWS_S3_REGION
  signatureVersion: 'v4'

Retrieve last 100 lines logs

I know this is very old, but, for whoever it may helps.

less +F my_log_file.log

that's just basic, with less you can do lot more powerful things. once you start seeing logs you can do search, go to line number, search for pattern, much more plus it is faster for large files.

its like vim for logs[totally my opinion]

original less's documentation :

less cheatsheet :

How to search text using php if ($text contains "World")

In your case you can just use strpos(), or stripos() for case insensitive search:

if (stripos($text, "world") !== false) {
    echo "True";

Make just one slide different size in Powerpoint

Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.

The process to do so is as follows:

  1. Create the two Powerpoints (with your desired slide dimensions)
    • They need to be properly filled in to have linkable objects and selectable slides
  2. Select an object in the main PowerPoint to act as the hyperlink
  3. Go to "Insert -> Links -> Action"
  4. Select either the "Mouse Click" or the "Mouse Over" tab
  5. Select "Hyperlink to:" and in the drop down menu choose "other PowerPoint Presentation"
  6. Select the slide that you want to link to.
    • Any slide that isn't empty should appear in the "Hyperlink to Slide" dialog box
  7. Repeat the Process in the second Presentation to link back to your main presentation

Reference to Office Support Page where this solution was first posted.

How can I enable MySQL's slow query log without restarting MySQL?

I think the problem is making sure that MySQL server has the rights to the file and can edit it.

If you can get it to have access to the file, then you can try setting:
SET GLOBAL slow_query_log = 1;

If not, you can always 'reload' the server after changing the configuration file. On linux its usually /etc/init.d/mysql reload

Git clone particular version of remote repository


Since Git 2.5.0 this configuration variable can be enabled on the server, here the GitHub feature request and the GitHub commit enabling this feature.

Bitbucket Server enabled it since version 5.5+.


# Make remote with 4 commits, and local with just one.
mkdir server
cd server
git init
touch 1
git add 1
git commit -m 1
git clone ./ ../local
for i in {2..4}; do
    touch "$i"
    git add "$i"
    git commit -m "$i"

# Before last commit.
SHA3="$(git log --format='%H' --skip=1 -n1)"
# Last commit.
SHA4="$(git log --format='%H' -n1)"

# Failing control without feature.
cd ../local
# Does not give an error, but does not fetch either.
git fetch origin "$SHA3"
# Error.
git checkout "$SHA3"

# Enable the feature.
cd ../server
git config uploadpack.allowReachableSHA1InWant true

# Now it works.
cd ../local
git fetch origin "$SHA3"
git checkout "$SHA3"
# Error.
git checkout "$SHA4"

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Despite not fully answering the original question, this is probably what most people googling this wanted to see.

For GCC:

$ cat test.cpp 
#include <iostream>

int main(int argc, char **argv)
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
$ g++ test.cpp 
$ ./a.out 
int main(int, char**)

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

How to get a path to a resource in a Java JAR file

This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.

Anything you can do by getting a could be done by copying the stream out into a temporary file and doing the same, if a is absolutely necessary.

Android Preventing Double Click On A Button

You can use this method. By using post delay you can take care for double click events.

void debounceEffectForClick(View view) {


    view.postDelayed(new Runnable() {
        public void run() {

    }, 500);

rbenv not changing ruby version

I forgot to delete rvm before installing rbenv. I deleted rvm and re-installed rbenv, but system still wasn't using the version of Ruby being designated as global by rbenv. I tried shutting Terminal, but it only worked once I restarted the whole machine.

Correct way to find max in an Array in Swift

Swift 3.0

You can try this code programmatically.

func getSmallAndGreatestNumber() -> Void {

    let numbers = [145, 206, 116, 809, 540, 176]
    var i = 0
    var largest = numbers[0]
    var small = numbers[0]
    while i < numbers.count{

        if (numbers[i] > largest) {
            largest = numbers[i]
        if (numbers[i] < small) {
            small = numbers[i]
        i = i + 1
    print("Maximum Number ====================\(largest)")// 809
    print("Minimum Number ====================\(small)")// 116

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

Here is what I wrote based on info found on this forum:

This is part of a MyDebugNamespace, Debug is apparently reserved and won't do as namespace name.

    var DEBUG = true;


    if (true == DEBUG && !test)
        var sAlert = "Assertion failed! ";
        if (null != message)
            sAlert += "\n" + message;
        if (null != err)
            sAlert += "\n" + "File: " + err.fileName + "\n" + "Line: " + err.lineNumber;


How to call:

    MyDebugNamespace.Assert(new Error(""), (null != someVar), "Something is wrong!")

I included two functions with variable number of arguments calling this base code in my namespace so as to optionally omit message or error in calls.

This works fine with Firefox, IE6 and Chrome report the fileName and lineNumber as undefined.

Resource u'tokenizers/punkt/english.pickle' not found

For me nothing of the above worked, so I just downloaded all the files by hand from the web site and I put them also by hand in a file "tokenizers" inside of "nltk_data" folder. Not a pretty solution but still a solution.

Unique constraint violation during insert: why? (Oracle)

Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.

Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error.

You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a

SELECT <<sequence name>>.nextval
  FROM dual

and comparing that to

  FROM cmdb_db

If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1.

What is stability in sorting algorithms and why is it important?

Some more examples of the reason for wanting stable sorts. Databases are a common example. Take the case of a transaction data base than includes last|first name, date|time of purchase, item number, price. Say the data base is normally sorted by date|time. Then a query is made to make a sorted copy of the data base by last|first name, since a stable sort preserves the original order, even though the inquiry compare only involves last|first name, the transactions for each last|first name will be in data|time order.

A similar example is classic Excel, which limited sorts to 3 columns at a time. To sort 6 columns, a sort is done with the least significant 3 columns, followed by a sort with the most significant 3 columns.

A classic example of a stable radix sort is a card sorter, used to sort by a field of base 10 numeric columns. The cards are sorted from least significant digit to most significant digit. On each pass, a deck of cards is read and separated into 10 different bins according to the digit in that column. Then the 10 bins of cards are put back into the input hopper in order ("0" cards first, "9" cards last). Then another pass is done by the next column, until all columns are sorted. Actual card sorters have more than 10 bins since there are 12 zones on a card, a column can be blank, and there is a mis-read bin. To sort letters, 2 passes per column are needed, 1st pass for digit, 2nd pass for the 12 11 zone.

Later (1937) there were card collating (merging) machines that could merge two decks of cards by comparing fields. The input was two already sorted decks of cards, a master deck and an update deck. The collator merged the two decks into a a new mater bin and an archive bin, which was optionally used for master duplicates so that the new master bin would only have update cards in case of duplicates. This was probably the basis for the idea behind the original (bottom up) merge sort.

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

C++ -- expected primary-expression before ' '


int wordLength = wordLengthFunction(string word);


int wordLength = wordLengthFunction(word);

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city =

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city =

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

How to Populate a DataTable from a Stored Procedure

You can use a SqlDataAdapter:

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
    cmd.CommandType = CommandType.StoredProcedure;
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable();

What exactly is \r in C language?

'\r' is the carriage return character. The main times it would be useful are:

  1. When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.

  2. When writing to an interactive terminal on stdout or stderr, '\r' can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.

The example code in your post is definitely a wrong way to use '\r'. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n' (newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).

Using SQL LIKE and IN together

u can even try this


CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
        INSERT INTO @Strings VALUES (@text)
    IF (@index > 1) 
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      SET @text = RIGHT(@text, (LEN(@text) - @index))


select * from my_table inner join (select value from fn_split('M510', 'M615', 'M515', 'M612',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

TLDR; range is an arithmetic series so it can very easily calculate whether the object is there.It could even get the index of it if it were list like really quickly.

How can I check whether Google Maps is fully loaded?

You could check the GMap2.isLoaded() method every n milliseconds to see if the map and all its tiles were loaded (window.setTimeout() or window.setInterval() are your friends).

While this won't give you the exact event of the load completion, it should be good enough to trigger your Javascript.

Request UAC elevation from within a Python script?

Just adding this answer in case others are directed here by Google Search as I was. I used the elevate module in my Python script and the script executed with Administrator Privileges in Windows 10.

javac: file not found: Usage: javac <options> <source files>

SET path of JRE as well

jre is nothing but responsible for execute the program

PATH Variable value:

C:\Program Files\Java\jdk1.8.0\bin;C:\Program Files\Java\jre\bin;.;

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

Difference between readFile() and readFileSync()

'use strict'
var fs = require("fs");

 * implementation of readFileSync
var data = fs.readFileSync('input.txt');
console.log("Program Ended");

 * implementation of readFile 
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);

console.log("Program Ended");

For better understanding run the above code and compare the results..

Where is android studio building my .apk file?

in android 3.1.0 Above use below path to find signed version of APK

home/AndroidStudioProjects/<projedct name>/app/app-release.apk

and in windows

AndroidStudioProjects\{project name}\app\release\app-release.apk

C++ correct way to return pointer to array from function

In a real app, the way you returned the array is called using an out parameter. Of course you don't actually have to return a pointer to the array, because the caller already has it, you just need to fill in the array. It's also common to pass another argument specifying the size of the array so as to not overflow it.

Using an out parameter has the disadvantage that the caller may not know how large the array needs to be to store the result. In that case, you can return a std::vector or similar array class instance.

LINQ: Select an object and change some properties without creating a new object

I prefer this one. It can be combined with other linq commands.

from item in list
let xyz = item.PropertyToChange = calcValue()
select item

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
 $('#cmd').click(function () {
        var doc = new jsPDF();
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){'sample-file.pdf'); }


and it will work.

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

How can I test a change made to Jenkinsfile locally?

Aside from the Replay feature that others already mentioned (ditto on its usefulness!), I found the following to be useful as well:

  1. Create a test Pipeline job where you can type in Pipeline code or point to your repo/branch of a Jenkinsfile to quickly test out something. For more accurate testing, use a Multibranch Pipeline that points to your own fork where you can quickly make changes and commit without affecting prod. Stuff like BRANCH_NAME env is only available in Multibranch.
  2. Since Jenkinsfile is Groovy code, simply invoke it with "groovy Jenkinsfile" to validate basic syntax.

Set default value of javascript object attributes

Or you can try this

dict = {
 'somekey': 'somevalue'

val = dict['anotherkey'] || 'anotherval';

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

Don't know if anyone searches for this. I had the same problem. A select on the query and then doing the where (or join) and using the select variable solved the problem for me. (problem was in the collection "Reintegraties" for me)

query.Select(zv => new
                rId = zv.this.Reintegraties.FirstOrDefault().Id
            .Where(x => !db.Taken.Any(t => t.HoortBijEntiteitId == x.rId
                                             && t.HoortBijEntiteitType == EntiteitType.Reintegratie
                                             && t.Type == TaakType))
            .Select(x => x.zv);

hope this helps anyone.

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

C# Regex for Guid

I use an easier regex pattern


How to add buttons at top of map fragment API v2 layout

Button Above The Map

If this is what you want ...simply add button inside the Fragment.

<fragment xmlns:android=""

        android:text="Demo Button" 


How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

How to combine two strings together in PHP?

No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :)

$string = "the color is ";
$string .= "red";

echo $string; // gives: the color is red

Fatal error: Class 'PHPMailer' not found

all answers are outdated now. Most current version (as of Feb 2018) does not have autoload anymore, and PHPMailer should be initialized as follows:



    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $mail->IsSMTP(); // enable SMTP

    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = "";
    $mail->Port = 465; // or 587
    $mail->Username = "xxxxxx";
    $mail->Password = "xxxx";
    $mail->SetFrom("[email protected]");
    $mail->Subject = "Test";
    $mail->Body = "hello";
    $mail->AddAddress("[email protected]");

     if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
     } else {
        echo "Message has been sent";

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Courtesy of JDiApice who synthesized and extended the work of other contributors at iOS 8.x modal scroll issue #14839:

@media only screen and (max-device-width:768px) {

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;

body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute;

body {
    overflow-x: hidden;
    overflow-y: scroll !important;

/* The reason the media specific is on there is 
   on a desktop i was having issues with when the modal would open 
   all content on the page would shift from centered to left. 
   Looked like crap. So this targets up to tablet size devices 
   where you would need to scroll. There is still a slight shift 
   on mobile and tablet but its really not much. */

Unlike the other solutions we tried, it does not scroll the background to the top after the popup modal closes.

selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)


The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

Setting up an MS-Access DB for multi-user access

Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:

  1. No Locks
  2. All Records
  3. Edited Record

You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.

Transactions shouldn't be a problem if you use them correctly.

Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.

See other answers for Oracle comparison.

Any easy way to use icons from resources?

On Form_Load:

this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;

How to declare and display a variable in Oracle

If you are using pl/sql then the following code should work :

set server output on -- to retrieve and display a buffer


    v_text VARCHAR2(10); -- declare

    v_text := 'Hello';  --assign
    dbms_output.Put_line(v_text); --display


-- this must be use to execute pl/sql script

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

You should add a scroll to the page to select all elements using Selenium.executeScript("window.scrollBy(0,450)", "").

If you have a large list, add the scroll several times through the execution. Note the scroll only go to a certain point in the page for example (0,450).

shared global variables in C

There is a cleaner way with just one header file so it is simpler to maintain. In the header with the global variables prefix each declaration with a keyword (I use common) then in just one source file include it like this

#define common
#include "globals.h"
#undef common

and any other source files like this

#define common extern
#include "globals.h"
#undef common

Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this

#pragma once
common int globala;
common int globalb;

seems to work for any type of declaration. Don't use the common keyword on #define of course.

Android Studio Gradle Configuration with name 'default' not found

For me it turned out to be an relative symbolic link (to the referenced project) that couldn't be used by grade. (I was referencing a library). Thats a pretty edgy edge-case but maybe it helps someone in the future.

I solved it by putting a absolute symbolic link.

Before ln -s ../library after ln -s /the/full/path/to/the/library

What are the different types of keys in RDBMS?

There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.

AngularJS - get element attributes values

You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB

function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_

How to pass an array into a function, and return the results with an array

You are not able to return 'multiple values' in PHP. You can return a single value, which might be an array.

function foo($test1, $test2, $test3)
    return array($test1, $test2, $test3);
$test1 = "1";
$test2 = "2";
$test3 = "3";

$arr = foo($test1, $test2, $test3);

$test1 = $arr[0];
$test2 = $arr[1];
$test3 = $arr[2];

Super-simple example of C# observer/observable with delegates

Applying the Observer Pattern with delegates and events in c# is named "Event Pattern" according to MSDN which is a slight variation.

In this Article you will find well structured examples of how to apply the pattern in c# both the classic way and using delegates and events.

Exploring the Observer Design Pattern

public class Stock

    //declare a delegate for the event
    public delegate void AskPriceChangedHandler(object sender,
          AskPriceChangedEventArgs e);
    //declare the event using the delegate
    public event AskPriceChangedHandler AskPriceChanged;

    //instance variable for ask price
    object _askPrice;

    //property for ask price
    public object AskPrice

            //set the instance variable
            _askPrice = value;

            //fire the event

    }//AskPrice property

    //method to fire event delegate with proper name
    protected void OnAskPriceChanged()

        AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice));


}//Stock class

//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs : EventArgs

    //instance variable to store the ask price
    private object _askPrice;

    //constructor that sets askprice
    public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; }

    //public property for the ask price
    public object AskPrice { get { return _askPrice; } }


Is it possible to use jQuery to read meta tags

Just use something like:

var author = $('meta[name=author]').attr('content');

What does the 'static' keyword do in a class?

A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using static the field becomes a class variable, thus there is one and only one clock. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.

GridView sorting: SortDirection always Ascending

Wrote this, it works for me:

 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        if (ViewState["sortExpression"] == null || ViewState["sortExpression"].ToString() != e.SortExpression.ToString())
            MyDataTable.DefaultView.Sort = e.SortExpression + " ASC";
            if (ViewState["SortDirection"].ToString() == "Ascending")
                MyDataTable.DefaultView.Sort = e.SortExpression = e.SortExpression + " DESC";
                MyDataTable.DefaultView.Sort = e.SortExpression + " ASC";

        GridView1.DataSource = MyDataTable;

        ViewState["sortExpression"] = e.SortExpression;
        ViewState["SortDirection"] = e.SortDirection;

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]


setDT(dt)[J(vc), on=.(fct), nomatch = 0]

Big O, how do you calculate/approximate it?

As to "how do you calculate" Big O, this is part of Computational complexity theory. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.

If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found Amortized analysis very useful in practice.

Random integer in VB.NET

Use System.Random:

Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer

' Create a random number generator
Dim Generator As System.Random = New System.Random()

' Get a random number >= MyMin and <= MyMax
My1stRandomNumber = Generator.Next(MyMin, MyMax + 1) ' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value

' Get another random number (don't create a new generator, use the same one)
My2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)

How to fluently build JSON in Java?

it's much easier than you think to write your own, just use an interface for JsonElementInterface with a method string toJson(), and an abstract class AbstractJsonElement implementing that interface,

then all you have to do is have a class for JSONProperty that implements the interface, and JSONValue(any token), JSONArray ([...]), and JSONObject ({...}) that extend the abstract class

JSONObject has a list of JSONProperty's
JSONArray has a list of AbstractJsonElement's

your add function in each should take a vararg list of that type, and return this

now if you don't like something you can just tweak it

the benifit of the inteface and the abstract class is that JSONArray can't accept properties, but JSONProperty can accept objects or arrays

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

In Python, how do I iterate over a dictionary in sorted key order?

Haven't tested this very extensively, but works in Python 2.5.2.

>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
('a', 2222)
('h', 15)
('x', 2)

If you are used to doing for key, value in d.iteritems(): ... instead of iterators, this will still work with the solution above

>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)

With Python 3.x, use d.items() instead of d.iteritems() to return an iterator.

Disable Logback in SpringBoot

Correct way to exclude default logging, and configure log4j for logging.


Refer Spring Logging - How To.

In gradle, I needed to do this with several other dependencies:

configurations {
    all*.exclude module : 'spring-boot-starter-logging'
    all*.exclude module : 'logback-classic'

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;

Close Bootstrap Modal


use the above code to hide the backdrop of modal if you are using multiple modal pop in one page.

Opening Android Settings programmatically

You can try to call:

startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));

for other screen in setting screen, you can go to

Hope help you in this case.

Remove specific characters from a string in Javascript

Simply replace it with nothing:

var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'


A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;

How to insert an element after another element in JavaScript without using a library?

if( !Element.prototype.insertAfter ) {
    Element.prototype.insertAfter = function(item, reference) {
        if( reference.nextSibling )
            reference.parentNode.insertBefore(item, reference.nextSibling);

github markdown colspan

Adding break resolves your issue. You can store more than a record in a cell as markdown doesn't support much features.

Map<String, String>, how to print both the "key string" and "value string" together

final Map<String, String> mss1 = new ProcessBuilder().environment();
        //depending on how you want to join K and V use different delimiter
        .map(entry -> 
        String.join(":", entry.getKey(),entry.getValue()))

Putting HTML inside Html.ActionLink(), plus No Link Text?

I ended up with a custom extension method. Its worth noting, when trying to place HTML inside of an Anchor object, the link text can be either to the left, or to the right of the inner HTML. For this reason, I opted to provide parameters for left and right inner HTML - the link text is in the middle. Both left and right inner HTML are optional.

Extension Method ActionLinkInnerHtml:

    public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);

        var builder = new TagBuilder("a");
        builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
        builder.MergeAttribute(key: "href", value: url);

        builder.MergeAttributes(htmlAttributes, replaceExisting: true);

        var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
        return mvcHtmlString;

Example of Usage:

Here is an example of usage. For this example I only wanted the inner html on the right side of the link text...

    linkText: "Hello World"
        , actionName: "SomethingOtherThanIndex"
        , controllerName: "SomethingOtherThanHome"
        , rightInnerHtml: "<span class=\"caret\" />"


this results in the following HTML...

<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>

jQuery vs. javascript?

Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.

I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.

I definitely recommend JQuery!


What is the difference between procedural programming and functional programming?


In Haskell there is a library function called product:

prouduct list = foldr 1 (*) list

or simply:

product = foldr 1 (*)

so the "idiomatic" factorial

fac n = foldr 1 (*)  [1..n]

would simply be

fac n = product [1..n]

Upgrading React version and it's dependencies by reading package.json

If you want to update react use npx update react on the terminal.

Can we cast a generic object to a custom object type in javascript?


But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

How do I set the selected item in a drop down box

Simple way

<select class ="dropdownstyle" name="category" selected="<?php print($messageeditdetails[0]['category_id']); ?>">

<option value=""><?php echo "Select"; ?></option>

<?php  foreach ($dropdowndetails as $dropdowndetails) { ?>
    <option <?php if($messageeditdetails[0]['category_id'] == $dropdowndetails['id']) { ?> selected="<?php echo $dropdowndetails['id']; ?>" <?php } ?> value="<?php echo $dropdowndetails['id']; ?>"><?php echo $dropdowndetails['category_name']; ?></option>
<?php } ?>