Programs & Examples On #Drupal commons

Drupal Commons is a distribution that provides a complete social business software solution for organizations.

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

In vim, use command:

:%s/\r\n/\r/g

Where you want to search and replace:

\r\n

into

\r

and the

/g

is for global

Note that this is the same as the answer by @ContextSwitch but with the gobal flag

How to use ESLint with Jest

In your .eslintignore file add the following value:

**/__tests__/

This should ignore all instances of the __tests__ directory and their children.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

What does file:///android_asset/www/index.html mean?

The URI "file:///android_asset/" points to YourProject/app/src/main/assets/.

Note: android_asset/ uses the singular (asset) and src/main/assets uses the plural (assets).

Suppose you have a file YourProject/app/src/main/assets/web_thing.html that you would like to display in a WebView. You can refer to it like this:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");

The snippet above could be located in your Activity class, possibly in the onCreate method.

Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.

bundle install fails with SSL certificate verification error

The simplest solution:

rvm pkg install openssl
rvm reinstall all --force

Voila!

Check to see if python script is running

My solution is to check for the process and command line arguments Tested on windows and ubuntu linux

import psutil
import os

def is_running(script):
    for q in psutil.process_iter():
        if q.name().startswith('python'):
            if len(q.cmdline())>1 and script in q.cmdline()[1] and q.pid !=os.getpid():
                print("'{}' Process is already running".format(script))
                return True

    return False


if not is_running("test.py"):
    n = input("What is Your Name? ")
    print ("Hello " + n)

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

Subtract minute from DateTime in SQL Server 2005

I spent a while trying to do the same thing, trying to subtract the hours:minutes from datetime - here's how I did it:

convert( varchar, cast((RouteMileage / @average_speed) as integer))+ ':' +  convert( varchar, cast((((RouteMileage / @average_speed) - cast((RouteMileage / @average_speed) as integer)) * 60) as integer)) As TravelTime,

dateadd( n, -60 * CAST( (RouteMileage / @average_speed) AS DECIMAL(7,2)), @entry_date) As DepartureTime 

OUTPUT:

DeliveryDate                TravelTime             DepartureTime
2012-06-02 12:00:00.000       25:49         2012-06-01 10:11:00.000

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

How to create a number picker dialog?

For kotlin lovers.

fun numberPickerCustom() {
    val d = AlertDialog.Builder(context)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.number_picker_dialog, null)
    d.setTitle("Title")
    d.setMessage("Message")
    d.setView(dialogView)
    val numberPicker = dialogView.findViewById<NumberPicker>(R.id.dialog_number_picker)
    numberPicker.maxValue = 15
    numberPicker.minValue = 1
    numberPicker.wrapSelectorWheel = false
    numberPicker.setOnValueChangedListener { numberPicker, i, i1 -> println("onValueChange: ") }
    d.setPositiveButton("Done") { dialogInterface, i ->
        println("onClick: " + numberPicker.value)       
        }
    d.setNegativeButton("Cancel") { dialogInterface, i -> }
    val alertDialog = d.create()
    alertDialog.show()
}

and number_picker_dialog.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal">

    <NumberPicker
        android:id="@+id/dialog_number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

If Python is interpreted, what are .pyc files?

THIS IS FOR BEGINNERS,

Python automatically compiles your script to compiled code, so called byte code, before running it.

Running a script is not considered an import and no .pyc will be created.

For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.

If you need to create a .pyc file for a module that is not imported, you can use the py_compile and compileall modules.

The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:

>>> import py_compile
>>> py_compile.compile('abc.py')

This will write the .pyc to the same location as abc.py (you can override that with the optional parameter cfile).

You can also automatically compile all files in a directory or directories using the compileall module.

python -m compileall

If the directory name (the current directory in this example) is omitted, the module compiles everything found on sys.path

How to convert all tables from MyISAM into InnoDB?

In the scripts below, replace <username>, <password> and <schema> with your specific data.

To show the statements that you can copy-paste into a mysql client session type the following:

echo 'SHOW TABLES;' \
 | mysql -u <username> --password=<password> -D <schema> \
 | awk '!/^Tables_in_/ {print "ALTER TABLE `"$0"` ENGINE = InnoDB;"}' \
 | column -t \

To simply execute the change, use this:

echo 'SHOW TABLES;' \
 | mysql -u <username> --password=<password> -D <schema> \
 | awk '!/^Tables_in_/ {print "ALTER TABLE `"$0"` ENGINE = InnoDB;"}' \
 | column -t \
 | mysql -u <username> --password=<password> -D <schema>

CREDIT: This is a variation of what was outlined in this article.

How to make my layout able to scroll down?

If you even did not get scroll after doing what is written above .....

Set the android:layout_height="250dp"or you can say xdp where x can be any numerical value.

How to do a GitHub pull request

I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:

git push -u origin <branch>

Broadcast receiver for checking internet connection in android app

1) In manifest : - call receiver like below code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.safal.checkinternet">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2) Make one Broad Cast Receiver Class: - In This class add code of Network Check

package com.safal.checkinternet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (isOnline(context)){
            Toast.makeText(context, "Available", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(context, "Not Available", Toast.LENGTH_SHORT).show();
        }
    }
    public boolean isOnline(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return (netInfo != null && netInfo.isConnected());
    }    
} 

3) In your Activity call to Broad Cast Receiver : -

package com.safal.checkinternet;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//Call Broad cast Receiver 
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(new NetworkChangeReceiver(), filter);
    }
}

Clearing all cookies with JavaScript

You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.

Assign a variable inside a Block to a variable outside a Block

yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.

How generate unique Integers based on GUIDs

Because the GUID space is larger than the number of 32-bit integers, you're guaranteed to have collisions if you have enough GUIDs. Given that you understand that and are prepared to deal with collisions, however rare, GetHashCode() is designed for exactly this purpose and should be preferred.

Best way to unselect a <select> in jQuery?

$("#selectID option:selected").each(function(){
  $(this).removeAttr("selected");
});

This would iterate through each item and unselect only the ones which are checked

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

iPhone hide Navigation Bar only on first page

Another approach I found is to set a delegate for the NavigationController:

navigationController.delegate = self;

and use setNavigationBarHidden in navigationController:willShowViewController:animated:

- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController 
                    animated:(BOOL)animated 
{   
    // Hide the nav bar if going home.
    BOOL hide = viewController != homeViewController;
    [navigationController setNavigationBarHidden:hide animated:animated];
}

Easy way to customize the behavior for each ViewController all in one place.

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

How to drop rows from pandas data frame that contains a particular string in a particular column?

The below code will give you list of all the rows:-

df[df['C'] != 'XYZ']

To store the values from the above code into a dataframe :-

newdf = df[df['C'] != 'XYZ']

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Not able to start Genymotion device

In my case, I restart the computer and enable the virtualization technology in BIOS. Then start up computer, open VM Virtual Box, choose a virtual device, go to Settings-General-Basic-Version, choose ubuntu(64 bit), save the settings then start virtual device from genymotion, everything is ok now.

Unable to connect PostgreSQL to remote database using pgAdmin

In linux terminal try this:

  • sudo service postgresql start : to start the server
  • sudo service postgresql stop : to stop thee server
  • sudo service postgresql status : to check server status

Random integer in VB.NET

All the answers so far have problems or bugs (plural, not just one). I will explain. But first I want to compliment Dan Tao's insight to use a static variable to remember the Generator variable so calling it multiple times will not repeat the same # over and over, plus he gave a very nice explanation. But his code suffered the same flaw that most others have, as i explain now.

MS made their Next() method rather odd. the Min parameter is the inclusive minimum as one would expect, but the Max parameter is the exclusive maximum as one would NOT expect. in other words, if you pass min=1 and max=5 then your random numbers would be any of 1, 2, 3, or 4, but it would never include 5. This is the first of two potential bugs in all code that uses Microsoft's Random.Next() method.

For a simple answer (but still with other possible but rare problems) then you'd need to use:

Private Function GenRandomInt(min As Int32, max As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    Return staticRandomGenerator.Next(min, max + 1)
End Function

(I like to use Int32 rather than Integer because it makes it more clear how big the int is, plus it is shorter to type, but suit yourself.)

I see two potential problems with this method, but it will be suitable (and correct) for most uses. So if you want a simple solution, i believe this is correct.

The only 2 problems i see with this function is: 1: when Max = Int32.MaxValue so adding 1 creates a numeric overflow. altho, this would be rare, it is still a possibility. 2: when min > max + 1. when min = 10 and max = 5 then the Next function throws an error. this may be what you want. but it may not be either. or consider when min = 5 and max = 4. by adding 1, 5 is passed to the Next method, but it does not throw an error, when it really is an error, but Microsoft .NET code that i tested returns 5. so it really is not an 'exclusive' max when the max = the min. but when max < min for the Random.Next() function, then it throws an ArgumentOutOfRangeException. so Microsoft's implementation is really inconsistent and buggy too in this regard.

you may want to simply swap the numbers when min > max so no error is thrown, but it totally depends on what is desired. if you want an error on invalid values, then it is probably better to also throw the error when Microsoft's exclusive maximum (max + 1) in our code equals minimum, where MS fails to error in this case.

handling a work-around for when max = Int32.MaxValue is a little inconvenient, but i expect to post a thorough function which handles both these situations. and if you want different behavior than how i coded it, suit yourself. but be aware of these 2 issues.

Happy coding!

Edit: So i needed a random integer generator, and i decided to code it 'right'. So if anyone wants the full functionality, here's one that actually works. (But it doesn't win the simplest prize with only 2 lines of code. But it's not really complex either.)

''' <summary>
''' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.
''' </summary>
''' <param name="inMin">Inclusive Minimum value. Lowest possible return value.</param>
''' <param name="inMax">Inclusive Maximum value. Highest possible return value.</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    If inMin > inMax Then Dim t = inMin : inMin = inMax : inMax = t
    If inMax < Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)
    ' now max = Int32.MaxValue, so we need to work around Microsoft's quirk of an exclusive max parameter.
    If inMin > Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 ' okay, this was the easy one.
    ' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.
    ' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.
    Dim bytes(3) As Byte ' 4 bytes, 0 to 3
    staticRandomGenerator.NextBytes(bytes) ' 4 random bytes
    Return BitConverter.ToInt32(bytes, 0) ' return bytes converted to a random Int32
End Function

How do I detect a click outside an element?

if you just want to display a window when you click on a button and undisp this window when you click outside.( or on the button again ) this bellow work good

document.body.onclick = function() { undisp_menu(); };
var menu_on = 0;

function menu_trigger(event){

    if (menu_on == 0)
    {
        // otherwise u will call the undisp on body when 
        // click on the button
        event.stopPropagation(); 

        disp_menu();
    }

    else{
        undisp_menu();
    }

}


function disp_menu(){

    menu_on = 1;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu on";

}

function undisp_menu(){

    menu_on = 0;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu";

}

don't forget this for the button

<div class="button" onclick="menu_trigger(event)">

<div class="menu">

and the css:

.menu{
    display: none;
}

.on {
    display: inline-block;
}

Recover unsaved SQL query scripts

I use the free file searching program Everything, search for *.sql files across my C: drive, and then sort by Last Modified, and then browse by the date I think it was probably last executed.

It usually brings up loads of autorecovery files from a variety of locations. And you don't have to worry where the latest version of SSMS/VS is saving the backup files this version.

enter image description here

window.open with target "_blank" in Chrome

window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

Asp.net 4.0 has not been registered

Open:

Start Menu
-> Programs
-> Microsoft Visual Studio 2010
-> Visual Studio Tools
-> Visual Studio Command Prompt (2010)

Run in command prompt:

aspnet_regiis -i

Make sure it is run at administrator, check that the title starts with Administrator:

enter image description here

Simple java program of pyramid

enter image description here

 import java.util.Scanner;
    public class Print {
        public static void main(String[] args) {
            int row,temp,c,n;
            Scanner s=new Scanner(System.in);
            n=s.nextInt();
            temp = n;
            for ( row = 1 ; row <= n ; row++ )
               {
                  for ( c = 1 ; c < temp ; c++ )
                    System.out.print(" ");

                  temp--;

                  for ( c = 1 ; c <= 2*row - 1 ; c++ )
                      System.out.print("*");

                  System.out.println("");
               }
        }

    }

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to generate XML file dynamically using PHP?

With FluidXML you can generate your XML very easly.

$tracks = fluidxml('xml');

$tracks->times(8, function ($i) {
    $this->add([
        'track' => [
            'path'  => "song{$i}.mp3",
            'title' => "Track {$i} - Track Title"
        ]
    ]);

});

https://github.com/servo-php/fluidxml

Android draw a Horizontal line between views

Try this

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

How do I uniquely identify computers visiting my web site?

When i use a machine which has never visited my online banking web site i get asked for additional authentification. then, if i go back a second time to the online banking site i dont get asked the additional authentification...i deleted all cookies in IE and relogged onto my online banking site fully expecting to be asked the authentification questions again. to my surprise i was not asked. doesnt this lead one to believe the bank is doing some kind of pc tagging which doesnt involve cookies?

This is a pretty common type of authentication used by banks.

Say you're accessing your bank website via example-isp.com. The first time you're there, you'll be asked for your password, as well as additional authentication. Once you've passed, the bank knows that user "thatisvaliant" is authenticated to access the site via example-isp.com.

In the future, it won't ask for extra authentication (beyond your password) when you're accessing the site via example-isp.com. If you try to access the bank via another-isp.com, the bank will go through the same routine again.

So to summarize, what the bank's identifying is your ISP and/or netblock, based on your IP address. Obviously not every user at your ISP is you, which is why the bank still asks you for your password.

Have you ever had a credit card company call to verify that things are OK when you use a credit card in a different country? Same concept.

How to unset (remove) a collection element after fetching it?

If you know the key which you unset then put directly by comma separated

unset($attr['placeholder'], $attr['autocomplete']);

How can I calculate the difference between two dates?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

int numberOfDays = secondsBetween / 86400;

NSLog(@"There are %d days in between the two dates.", numberOfDays);

EDIT:

Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.

How to squash all git commits into one?

create a backup

git branch backup

reset to specified commit

git reset --soft <#root>

then add all files to staging

git add .

commit without updating the message

git commit --amend --no-edit

push new branch with squashed commits to repo

git push -f

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

First off, add a suffix to the application package in Gradle:

yourFlavor {
   applicationIdSuffix "yourFlavor"
}

This will cause your package to be named

com.domain.yourapp.yourFlavor

Then go to Firebase under your current project and add another android app to it with this package name.

Then replace the existing google-services.json file with the new one you generate with the new app in it.

Then you will end up with something that has multiple "client_info" sections. So you should end up with something like this:

"client_info": {
    "mobilesdk_app_id": "YOUR APP INFO",
    "android_client_info": {
      "package_name": "com.domain.yourapp"
    }
  }

"client_info": {
    "mobilesdk_app_id": "YOUR APP INFO - will be different then other app info",
    "android_client_info": {
      "package_name": "com.domain.yourapp.yourFlavor"
    }
  }

LaTeX table too wide. How to make it fit?

Use p{width} column specifier: e.g. \begin{tabular}{ l p{10cm} } will put column's content into 10cm-wide parbox, and the text will be properly broken to several lines, like in normal paragraph.

You can also use tabular* environment to specify width for the entire table.

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

SQLite - getting number of rows in a database

If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want

SELECT COALESCE(MAX(id)+1, 0) FROM words

What is the difference between signed and unsigned variables?

unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How to copy a string of std::string type in C++?

strcpy example:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

How do I print the elements of a C++ vector in GDB?

To view vector std::vector myVector contents, just type in GDB:

(gdb) print myVector

This will produce an output similar to:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30}

To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki.

What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

Found shared references to a collection org.hibernate.HibernateException

My problem was that I had setup an @ManyToOne relationship. Maybe if the answers above don't fix your problem you might want to check the relationship that was mentioned in the error message.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If anyone wants to get installed application package code, just execute below command with your application name in the command prompt. You will be getting product code along with package code.

wmic product where "Name like '%YOUR_APPLICATION_NAME%'" get IdentifyingNumber, PackageCode

Programmatically go back to previous ViewController in Swift

I did it like this

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        self.dismissView()
    }))

    self.present(alert, animated: true)
}

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}

How to generate the JPA entity Metamodel?

It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know)

Yes it is. Here are the implementations and instructions for the various JPA 2.0 implementations:

EclipseLink

Hibernate

OpenJPA

DataNucleus


The latest Hibernate implementation is available at:

An older Hibernate implementation is at:

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Div Scrollbar - Any way to style it?

No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.

How do I read the source code of shell commands?

Actually more sane sources are provided by http://suckless.org look at their sbase repository:

git clone git://git.suckless.org/sbase

They are clearer, smarter, simpler and suckless, eg ls.c has just 369 LOC

After that it will be easier to understand more complicated GNU code.

How to install requests module in Python 3.4, instead of 2.7

You can specify a Python version for pip to use:

pip3.4 install requests

Python 3.4 has pip support built-in, so you can also use:

python3.4 -m pip install

If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3 separately:

sudo apt-get install python3-pip

This will install the pip3 executable, so you can use it, as well as the earlier mentioned python3.4 -m pip:

pip3 install requests

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

Configuring angularjs with eclipse IDE

  1. Make sure the project is extracted on your hard disk.
  2. In Eclipse go to the menu: File->New->Project.
  3. Select "General->Project" and click on the next button.
  4. Enter the project name in the "Project name:" field
  5. Disable "Use default location" Click on the "Browse ..." button and select the folder that contains the project (the one from step 1)
  6. Click on the "Finish" button
  7. Right-click with the mouse on you're new project and click "Configure->Convert to AngularJS Project.."
  8. Enable you're project goodies and click on the "OK" button.

How can I convert a date to GMT?

Although it looks logical, the accepted answer is incorrect because JavaScript dates don't work like that.

It's super important to note here that the numerical value of a date (i.e., new Date()-0 or Date.now()) in JavaScript is always measured as millseconds since the epoch which is a timezone-free quantity based on a precise exact instant in the history of the universe. You do not need to add or subtract anything to the numerical value returned from Date() to convert the numerical value into a timezone, because the numerical value has no timezone. If it did have a timezone, everything else in JavaScript dates wouldn't work.

Timezones, leap years, leap seconds, and all of the other endlessly complicated adjustments to our local times and dates, are based on this consistent and unambiguous numerical value, not the other way around.

Here are examples of how the numerical value of a date (provided to the date constructor) is independent of timezone:

In Central Standard Time:

new Date(0);
// Wed Dec 31 1969 18:00:00 GMT-0600 (CST)

In Anchorage, Alaska:

new Date(0);
// Wed Dec 31 1969 15:00:00 GMT-0900 (AHST)

In Paris, France:

new Date(0);
// Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

It is critical to observe that in ALL cases, based on the timezone-free epoch offset of zero milliseconds, the resulting time is identical. 1 am in Paris, France is the exact same moment as 3 pm the day before in Anchorage, Alaska, which is the exact same moment as 6 pm in Chicago, Illinois.

For this reason, the accepted answer on this page is incorrect. Observe:

// Create a date.
   date = new Date();
// Fri Jan 27 2017 18:16:35 GMT-0600 (CST)


// Observe the numerical value of the date.
   date.valueOf();
// 1485562595732
// n.b. this value has no timezone and does not need one!!


// Observe the incorrectly "corrected" numerical date value.
   date.valueOf() + date.getTimezoneOffset() * 60000;
// 1485584195732


// Try out the incorrectly "converted" date string.
   new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
// Sat Jan 28 2017 00:16:35 GMT-0600 (CST)

/* Not the correct result even within the same script!!!! */

If you have a date string in another timezone, no conversion to the resulting object created by new Date("date string") is needed. Why? JavaScript's numerical value of that date will be the same regardless of its timezone. JavaScript automatically goes through amazingly complicated procedures to extract the original number of milliseconds since the epoch, no matter what the original timezone was.

The bottom line is that plugging a textual date string x into the new Date(x) constructor will automatically convert from the original timezone, whatever that might be, into the timezone-free epoch milliseconds representation of time which is the same regardless of any timezone. In your actual application, you can choose to display the date in any timezone that you want, but do NOT add/subtract to the numerical value of the date in order to do so. All the conversion already happened at the instant the date object was created. The timezone isn't even there anymore, because the date object is instantiated using a precisely-defined and timezone-free sense of time.

The timezone only begins to exist again when the user of your application is considered. The user does have a timezone, so you simply display that timezone to the user. But this also happens automatically.

Let's consider a couple of the dates in your original question:

   date1 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300");
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)


   date2 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300")
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)

The console already knows my timezone, and so it has automatically shown me what those times mean to me.

And if you want to know the time in GMT/UTC representation, also no conversion is needed! You don't change the time at all. You simply display the UTC string of the time:

    date1.toUTCString();
// "Fri, 20 Jan 2012 14:51:36 GMT"

Code that is written to convert timezones numerically using the numerical value of a JavaScript date is almost guaranteed to fail. Timezones are way too complicated, and that's why JavaScript was designed so that you didn't need to.

Dynamic creation of table with DOM

You can create a dynamic table rows as below:

var tbl = document.createElement('table');
tbl.style.width = '100%';

for (var i = 0; i < files.length; i++) {

        tr = document.createElement('tr');

        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');

        ::::: // As many <td> you want

        td1.appendChild(document.createTextNode());
        td2.appendChild(document.createTextNode());
        td3.appendChild(document.createTextNode();

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbl.appendChild(tr);
}

How to disable the parent form when a child form is active?

@Melodia

Sorry for this is not C# code but this is what you would want, besides translating this should be easy.

FORM1

Private Sub Form1_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form2.Enabled = False
End Sub

Private Sub Form1_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form2.Enabled = True
    Form2.Focus()
End Sub

FORM2

Private Sub Form2_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form1.Enabled = False
End Sub

Private Sub Form2_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form1.Enabled = True
    Form1.Focus()
End Sub

Hope this helps

add item to dropdown list in html using javascript

For higher performance, I recommend this:

var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');

//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
    //var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
    option.text = option.value = i;
    options.push(option.outerHTML);
}

select.insertAdjacentHTML('beforeEnd', options.join('\n'));

This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.

Optional for generating the string by hand:

function escapeHTML(str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:

var docfrag = document.createDocumentFragment();

for (var i = 1900; i < 2012; ++i)
{
     docfrag.appendChild(new Option(i, i));
}

var select = document.getElementById("year");
select.appendChild(docfrag);

Add Variables to Tuple

It's as easy as the following:

info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")

However, tuples in Python are immutable, so you cannot append variables to a tuple once it is created.

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

jQuery OR Selector?

I have written an incredibly simple (5 lines of code) plugin for exactly this functionality:

http://byrichardpowell.github.com/jquery-or/

It allows you to effectively say "get this element, or if that element doesnt exist, use this element". For example:

$( '#doesntExist' ).or( '#exists' );

Whilst the accepted answer provides similar functionality to this, if both selectors (before & after the comma) exist, both selectors will be returned.

I hope it proves helpful to anyone who might land on this page via google.

How can I print the contents of an array horizontally?

The below solution is the simplest one:

Console.WriteLine("[{0}]", string.Join(", ", array));

Output: [1, 2, 3, 4, 5]

Another short solution:

Array.ForEach(array,  val => Console.Write("{0} ", val));

Output: 1 2 3 4 5. Or if you need to add add ,, use the below:

int i = 0;
Array.ForEach(array,  val => Console.Write(i == array.Length -1) ? "{0}" : "{0}, ", val));

Output: 1, 2, 3, 4, 5

Invoke-customs are only supported starting with android 0 --min-api 26

In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_10
    targetCompatibility JavaVersion.VERSION_1_10

}

Function names in C++: Capitalize or not?

I think its a matter of preference, although i prefer myFunction(...)

What is reflection and why is it useful?

I just want to add some point to all that was listed.

With Reflection API you can write universal toString() method for any object.

It is useful at debugging.

Here is some example:

class ObjectAnalyzer {

   private ArrayList<Object> visited = new ArrayList<Object>();

   /**
    * Converts an object to a string representation that lists all fields.
    * @param obj an object
    * @return a string with the object's class name and all field names and
    * values
    */
   public String toString(Object obj) {
      if (obj == null) return "null";
      if (visited.contains(obj)) return "...";
      visited.add(obj);
      Class cl = obj.getClass();
      if (cl == String.class) return (String) obj;
      if (cl.isArray()) {
         String r = cl.getComponentType() + "[]{";
         for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0) r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive()) r += val;
            else r += toString(val);
         }
         return r + "}";
      }

      String r = cl.getName();
      // inspect the fields of this class and all superclasses
      do {
         r += "[";
         Field[] fields = cl.getDeclaredFields();
         AccessibleObject.setAccessible(fields, true);
         // get the names and values of all fields
         for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
               if (!r.endsWith("[")) r += ",";
               r += f.getName() + "=";
               try {
                  Class t = f.getType();
                  Object val = f.get(obj);
                  if (t.isPrimitive()) r += val;
                  else r += toString(val);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }
         }
         r += "]";
         cl = cl.getSuperclass();
      } while (cl != null);

      return r;
   }    
}

POST request with a simple string in body with Alamofire

Xcode 8.X , Swift 3.X

Easy Use;

 let params:NSMutableDictionary? = ["foo": "bar"];
            let ulr =  NSURL(string:"http://mywebsite.com/post-request" as String)
            let request = NSMutableURLRequest(url: ulr! as URL)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)

            let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            if let json = json {
                print(json)
            }
            request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);


            Alamofire.request(request as! URLRequestConvertible)
                .responseJSON { response in
                    // do whatever you want here
                   print(response.request)  
                   print(response.response) 
                   print(response.data) 
                   print(response.result)

            }

Check Whether a User Exists

I was using it in that way:

if [ $(getent passwd $user) ] ; then
        echo user $user exists
else
        echo user $user doesn\'t exists
fi

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How return error message in spring mvc @Controller

    return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
    

    c++ exception : throwing std::string

    It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.

    Incidentally, throwing a std::string isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.

    Step out of current function with GDB

    You can use the finish command.

    finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

    (See 5.2 Continuing and Stepping.)

    Is it still valid to use IE=edge,chrome=1?

    It's still valid to use IE=edge,chrome=1.

    But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

    I use the following for correctness nowadays

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

    Select all from table with Laravel and Eloquent

    This worked for me.

    $posts = Blog::get()->all();
    

    CALL command vs. START with /WAIT option

    For exe files, I suppose the differences are nearly unimportant.
    But to start an exe you don't even need CALL.

    When starting another batch it's a big difference,
    as CALL will start it in the same window and the called batch has access to the same variable context.
    So it can also change variables which affects the caller.

    START will create a new cmd.exe for the called batch and without /b it will open a new window.
    As it's a new context, variables can't be shared.

    Differences

    Using start /wait <prog>
    - Changes of environment variables are lost when the <prog> ends
    - The caller waits until the <prog> is finished

    Using call <prog>
    - For exe it can be ommited, because it's equal to just starting <prog>
    - For an exe-prog the caller batch waits or starts the exe asynchronous, but the behaviour depends on the exe itself.
    - For batch files, the caller batch continues, when the called <batch-file> finishes, WITHOUT call the control will not return to the caller batch

    Addendum:

    Using CALL can change the parameters (for batch and exe files), but only when they contain carets or percent signs.

    call myProg param1 param^^2 "param^3" %%path%%
    

    Will be expanded to (from within an batch file)

    myProg param1 param2 param^^3 <content of path>
    

    R error "sum not meaningful for factors"

    The error comes when you try to call sum(x) and x is a factor.

    What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

    simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

    family[, 1] <- as.numeric(as.character( family[, 1] ))
    family[, 3] <- as.numeric(as.character( family[, 3] ))
    

    For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

    TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

    this worked for me - I did all of the above then changed:

    jdbc.databaseurl=jdbc:oracle:thin:@localhost:1521:xe
    

    to:

    jdbc.databaseurl=jdbc:oracle:thin:@localhost:1521/xe
    

    Spring Boot - Loading Initial Data

    You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.

    Installing a local module using npm?

    you just provide one <folder> argument to npm install, argument should point toward the local folder instead of the package name:

    npm install /path
    

    What's the most useful and complete Java cheat sheet?

    This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.

    For the complete API, however, I always use the Javadoc. I reference it constantly.

    Class name does not name a type in C++

    error 'Class' does not name a type
    

    Just in case someone does the same idiotic thing I did ... I was creating a small test program from scratch and I typed Class instead of class (with a small C). I didn't take any notice of the quotes in the error message and spent a little too long not understanding my problem.

    My search for a solution brought me here so I guess the same could happen to someone else.

    Jquery sortable 'change' event element position

    $( "#sortable" ).sortable({
        change: function(event, ui) {       
            var pos = ui.helper.index() < ui.placeholder.index() 
                ? { start: ui.helper.index(), end: ui.placeholder.index() }
                : { start: ui.placeholder.index(), end: ui.helper.index() }
    
            $(this)
                .children().removeClass( 'highlight' )
                .not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
        },
        stop: function(event, ui) {
            $(this).children().removeClass( 'highlight' );
        }
    });
    

    FIDDLE

    An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper, and the element of current position is ui.placeholder, we can take the elements between those two indexes and highlight them. Also, we can use this inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.

    How to add an image to the emulator gallery in android studio?

    I had the same problem too. I used this code:

    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    

    Using the ADM, add the images on the sdcard or anywhere.

    And when you are in your vm and the selection screen shows up, browse using the top left dropdown seen in the image below.

    look at 'open from'

    Get all child elements

    Yes, you can achieve it by find_elements_by_css_selector("*") or find_elements_by_xpath(".//*").

    However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.

    from selenium import webdriver
    
    driver = webdriver.Firefox()
    driver.get("http://www.stackoverflow.com")
    
    header = driver.find_element_by_id("header")
    
    # start from your target element, here for example, "header"
    all_children_by_css = header.find_elements_by_css_selector("*")
    all_children_by_xpath = header.find_elements_by_xpath(".//*")
    
    print 'len(all_children_by_css): ' + str(len(all_children_by_css))
    print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))
    

    Validating Phone Numbers Using Javascript

    Try this I It's working.

    _x000D_
    _x000D_
    <form>_x000D_
    <input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digit mobile number" placeholder="Mobile number" required>_x000D_
    <button>_x000D_
    Save_x000D_
    </button>_x000D_
    </form>_x000D_
     
    _x000D_
    _x000D_
    _x000D_

    https://jsfiddle.net/guljarpd/12b7v330/

    How to set custom header in Volley Request

    Here is setting headers from github sample:

    StringRequest myReq = new StringRequest(Method.POST,
                           "http://ave.bolyartech.com/params.php",
                            createMyReqSuccessListener(),
                            createMyReqErrorListener()) {
    
     protected Map<String, String> getParams() throws 
             com.android.volley.AuthFailureError {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("param1", num1);
                            params.put("param2", num2);
                            return params;
                        };
                    };
                    queue.add(myReq);
    

    if (boolean == false) vs. if (!boolean)

    The first form, when used with an API that returns Boolean and compared against Boolean.FALSE, will never throw a NullPointerException.

    The second form, when used with the java.util.Map interface, also, will never throw a NullPointerException because it returns a boolean and not a Boolean.

    If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean that may be NULL.

    How can I format a list to print each element on a separate line in python?

    Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:

    from __future__ import print_function  # Py 2.6+; In Py 3k not needed
    
    mylist = ['10', 12, '14']    # Note that 12 is an int
    
    print(*mylist,sep='\n')
    

    Prints:

    10
    12
    14
    

    Eventually, print as Python statement will go away... Might as well start to get used to it.

    How to terminate process from Python using pid?

    I wanted to do the same thing as, but I wanted to do it in the one file.

    So the logic would be:

    • if a script with my name is running, kill it, then exit
    • if a script with my name is not running, do stuff

    I modified the answer by Bakuriu and came up with this:

    from os import getpid
    from sys import argv, exit
    import psutil  ## pip install psutil
    
    myname = argv[0]
    mypid = getpid()
    for process in psutil.process_iter():
        if process.pid != mypid:
            for path in process.cmdline():
                if myname in path:
                    print "process found"
                    process.terminate()
                    exit()
    
    ## your program starts here...
    

    Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

    I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

    DataSet panel (Report Data) in SSRS designer is gone

    With a report (rdl) file selected in your solution, select View and then Report Data.

    It is a shortcut of Ctrl+Alt+D.

    enter image description here

    PHP Notice: Undefined offset: 1 with array when reading data

    Change

    $data[$parts[0]] = $parts[1];
    

    to

    if ( ! isset($parts[1])) {
       $parts[1] = null;
    }
    
    $data[$parts[0]] = $parts[1];
    

    or simply:

    $data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
    

    Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

    According to php.net possible return values from explode:

    Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

    If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

    Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

    The ^ negates a character class:

    SELECT * FROM mytable WHERE REGEXP_LIKE(column_1, '[^A-Za-z]')
    

    Is log(n!) = T(n·log(n))?

    Remember that

    log(n!) = log(1) + log(2) + ... + log(n-1) + log(n)
    

    You can get the upper bound by

    log(1) + log(2) + ... + log(n) <= log(n) + log(n) + ... + log(n)
                                    = n*log(n)
    

    And you can get the lower bound by doing a similar thing after throwing away the first half of the sum:

    log(1) + ... + log(n/2) + ... + log(n) >= log(n/2) + ... + log(n) 
                                           = log(n/2) + log(n/2+1) + ... + log(n-1) + log(n)
                                           >= log(n/2) + ... + log(n/2)
                                            = n/2 * log(n/2) 
    

    Genymotion error at start 'Unable to load virtualbox'

    I also experienced this when I upgraded operating system from Windows 8 to Windows 8.1. Un-installing Virtualbox and re-installing worked for me.

    Disabling tab focus on form elements

    If you're dealing with an input element, I found it useful to set the pointer focus to back itself.

    $('input').on('keydown', function(e) { 
        if (e.keyCode == 9) {
            $(this).focus();
           e.preventDefault();
        }
    });
    

    Calling a javascript function in another js file

    // module.js
    export function hello() {
      return "Hello";
    }
    
    // main.js
    import {hello} from 'module'; // or './module'
    let val = hello(); // val is "Hello";
    

    reference from https://hype.codes/how-include-js-file-another-js-file

    Difference between string and char[] types in C++

    Arkaitz is correct that string is a managed type. What this means for you is that you never have to worry about how long the string is, nor do you have to worry about freeing or reallocating the memory of the string.

    On the other hand, the char[] notation in the case above has restricted the character buffer to exactly 256 characters. If you tried to write more than 256 characters into that buffer, at best you will overwrite other memory that your program "owns". At worst, you will try to overwrite memory that you do not own, and your OS will kill your program on the spot.

    Bottom line? Strings are a lot more programmer friendly, char[]s are a lot more efficient for the computer.

    Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

    Forget trying to decipher the example .ts - as others have said it is often incomplete.

    Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

    enter image description here

    You can quickly confirm the required modules:

    enter image description here

    Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

    Template parse errors:
    Can't bind to 'formControl' since it isn't a known property of 'input'. 
    

    Setting table row height

    try this:

    .topics tr { line-height: 14px; }

    How to change background color in the Notepad++ text editor?

    You may need admin access to do it on your system.

    1. Create a folder 'themes' in the Notepad++ installation folder i.e. C:\Program Files (x86)\Notepad++
    2. Search or visit pages like http://timtrott.co.uk/notepad-colour-schemes/ to download the favourite theme. It will be an SML file.
      • Note: I prefer Neon any day.
    3. Download the themes from the site and drag them to the themes folder.
      • Note: I was unable to copy-paste or create new files in 'themes' folder so I used drag and that worked.
    4. Follow the steps provided by @triforceofcourage to select the new theme in Notepad++ preferences.

    get value from DataTable

    It looks like you have accidentally declared DataType as an array rather than as a string.

    Change line 3 to:

    Dim DataType As String = myTableData.Rows(i).Item(1)
    

    That should work.

    Using {% url ??? %} in django templates

    Instead of importing the logout_view function, you should provide a string in your urls.py file:

    So not (r'^login/', login_view),

    but (r'^login/', 'login.views.login_view'),

    That is the standard way of doing things. Then you can access the URL in your templates using:

    {% url login.views.login_view %}
    

    Webpack "OTS parsing error" loading fonts

    For me the problem was my regex expression. The below did the trick to get bootstrap working:

    {
        test: /\.(woff|ttf|eot|svg)(\?v=[a-z0-9]\.[a-z0-9]\.[a-z0-9])?$/,
        loader: 'url-loader?limit=100000'
    },
    

    jquery clear input default value

    Unless you're really worried about older browsers, you could just use the new html5 placeholder attribute like so:

    <input type="text" name="email" placeholder="Email address" class="input" />
    

    What is 'Currying'?

    It can be a way to use functions to make other functions.

    In javascript:

    let add = function(x){
      return function(y){ 
       return x + y
      };
    };
    

    Would allow us to call it like so:

    let addTen = add(10);
    

    When this runs the 10 is passed in as x;

    let add = function(10){
      return function(y){
        return 10 + y 
      };
    };
    

    which means we are returned this function:

    function(y) { return 10 + y };
    

    So when you call

     addTen();
    

    you are really calling:

     function(y) { return 10 + y };
    

    So if you do this:

     addTen(4)
    

    it's the same as:

    function(4) { return 10 + 4} // 14
    

    So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:

    let addTwo = add(2)       // addTwo(); will add two to whatever you pass in
    let addSeventy = add(70)  // ... and so on...
    

    Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things 1. cache expensive operations 2. achieve abstractions in the functional paradigm.

    Imagine our curried function looked like this:

    let doTheHardStuff = function(x) {
      let z = doSomethingComputationallyExpensive(x)
      return function (y){
        z + y
      }
    }
    

    We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

    let finishTheJob = doTheHardStuff(10)
    finishTheJob(20)
    finishTheJob(30)
    

    We can get abstractions in a similar way.

    How can I get the size of an std::vector as an int?

    In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

    #include <vector>
    
    int main () {
        std::vector<int> v;
        auto size = v.size();
    }
    

    Your third call

    int size = v.size();
    

    triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

    int size = static_cast<int>(v.size());
    

    would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

    Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

    How to fix: Error device not found with ADB.exe

    It depends on windows system but usually:

    1. you go to system properties
    2. look at hardware devices
    3. Right click on the yellow (has to be yellow if it's driver problem) icon representing your mobile device
    4. select property
    5. Then go on the driver tab
    6. select update driver
    7. choose the bottom selection find on local computer
    8. then choose manually
    9. From the windows opened look for driver disk the bottom right button
    10. Choose the driver from the folder <sdk>\extras\google\usb_driver\i386 (or amd64 for and).
    11. Remember to uncheck the show only compatible hardware.
    12. Then choose the driver
    13. When windows warn your about possible incompatibility go on.

    For my mobile it works, but depend on your mobile if it work or not.

    Hope this help, bye.

    How to check if an object is an array?

    I have updated the jsperf fiddle with two alternative methods as well as error checking.

    It turns out that the method defining a constant value in the 'Object' and 'Array' prototypes is faster than any of the other methods. It is a somewhat surprising result.

    _x000D_
    _x000D_
    /* Initialisation */_x000D_
    Object.prototype.isArray = function() {_x000D_
      return false;_x000D_
    };_x000D_
    Array.prototype.isArray = function() {_x000D_
      return true;_x000D_
    };_x000D_
    Object.prototype._isArray = false;_x000D_
    Array.prototype._isArray = true;_x000D_
    _x000D_
    var arr = ["1", "2"];_x000D_
    var noarr = "1";_x000D_
    _x000D_
    /* Method 1 (function) */_x000D_
    if (arr.isArray()) document.write("arr is an array according to function<br/>");_x000D_
    if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");_x000D_
    /* Method 2 (value) - **** FASTEST ***** */_x000D_
    if (arr._isArray) document.write("arr is an array according to member value<br/>");_x000D_
    if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");
    _x000D_
    _x000D_
    _x000D_

    These two methods do not work if the variable takes the undefined value, but they do work if you are certain that they have a value. With regards to checking with performance in mind if a value is an array or a single value, the second method looks like a valid fast method. It is slightly faster than 'instanceof' on Chrome, twice as fast as the second best method in Internet Explorer, Opera and Safari (on my machine).

    Functions are not valid as a React child. This may happen if you return a Component instead of from render

    In my case, I was transport class component from parent and use it inside as a prop var, using typescript and Formik, and run well like this:

    Parent 1

    import Parent2 from './../components/Parent2/parent2'
    import Parent3 from './../components/Parent3/parent3'
    
    export default class Parent1 extends React.Component {
      render(){
        <React.Fragment>
          <Parent2 componentToFormik={Parent3} />
        </React.Fragment>
      }
    }
    

    Parent 2

    export default class Parent2 extends React.Component{
      render(){
        const { componentToFormik } = this.props
        return(
        <Formik 
          render={(formikProps) => {
            return(
              <React.fragment>
                {(new componentToFormik(formikProps)).render()}
              </React.fragment>
            )
          }}
        />
        )
      }
    }
    

    Java - Check if input is a positive integer, negative integer, natural number and so on.

    What about using the following:

    int number = input.nextInt();
    if (number < 0) {
        // negative
    } else {
       // it's a positive
    }
    

    PHP function ssh2_connect is not working

    If you are running a bomebrew on OSX, I used the following to install it:

    brew install php56-ssh2
    

    That worked for me. I pulled it from here. There should also be Ubuntu and OSX using mac port as well.

    How to fix git error: RPC failed; curl 56 GnuTLS

    Try to disable your IPV6 for that and disable after. I think this is your problem.

    Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

    use labelpad parameter:

    pl.xlabel("...", labelpad=20)
    

    or set it after:

    ax.xaxis.labelpad = 20
    

    Extract directory path and filename

    Use the basename command to extract the filename from the path:

    [/tmp]$ export fspec=/exp/home1/abc.txt 
    [/tmp]$ fname=`basename $fspec`
    [/tmp]$ echo $fname
    abc.txt
    

    Rails - How to use a Helper Inside a Controller

    In Rails 5+ you can simply use the function as demonstrated below with simple example:

    module ApplicationHelper
      # format datetime in the format #2018-12-01 12:12 PM
      def datetime_format(datetime = nil)
        if datetime
          datetime.strftime('%Y-%m-%d %H:%M %p')
        else
          'NA'
        end
      end
    end
    
    class ExamplesController < ApplicationController
      def index
        current_datetime = helpers.datetime_format DateTime.now
        raise current_datetime.inspect
      end
    end
    

    OUTPUT

    "2018-12-10 01:01 AM"
    

    Allow multi-line in EditText view in Android?

    Try this, add these lines to your edit text view, i'll add mine. make sure you understand it

    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"
    android:scrollbars="vertical"
    
    <EditText
        android:inputType="textMultiLine"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText_newprom_description"
        android:padding="10dp"
        android:lines="5"
        android:overScrollMode="always"
        android:scrollbarStyle="insideInset"
        android:minLines="5"
        android:gravity="top|left"
        android:scrollbars="vertical"
        android:layout_marginBottom="20dp"/>
    

    and on your java class make on click listner to this edit text as follows, i'll add mine, chane names according to yours.

    EditText description;
    description = (EditText)findViewById(R.id.editText_newprom_description);
    
    description.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
    
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK){
                        case MotionEvent.ACTION_UP:
                            view.getParent().requestDisallowInterceptTouchEvent(false);
                            break;
                    }
    
                    return false;
                }
    
            });
    

    this works fine for me

    Selenium 2.53 not working on Firefox 47

    Firefox 47.0 stopped working with Webdriver.

    Easiest solution is to switch to Firefox 47.0.1 and Webdriver 2.53.1. This combination again works. In fact, restoring Webdriver compatibility was the main reason behind the 47.0.1 release, according to https://www.mozilla.org/en-US/firefox/47.0.1/releasenotes/.

    How do I check CPU and Memory Usage in Java?

    If you are looking specifically for memory in JVM:

    Runtime runtime = Runtime.getRuntime();
    
    NumberFormat format = NumberFormat.getInstance();
    
    StringBuilder sb = new StringBuilder();
    long maxMemory = runtime.maxMemory();
    long allocatedMemory = runtime.totalMemory();
    long freeMemory = runtime.freeMemory();
    
    sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
    sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
    sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
    sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>");
    

    However, these should be taken only as an estimate...

    What is the best way to detect a mobile device?

    Utilized previously mentioned sequielo solution and added the function for width/height check (to avoid screen rotation mistake). For selecting min/max borders for mobile viewport, I use this resource https://www.mydevice.io/#compare-devices

    function isMobile() {
        try{ document.createEvent("TouchEvent"); return true; }
        catch(e){ return false; }
    }
    
    function deviceType() {
        var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),screenType;
        if (isMobile()){
            if ((width <= 650 && height <= 900) || (width <= 900 && height <= 650))
                screenType = "Mobile Phone";
            else
                screenType = "Tablet";
        }
        else
            screenType = "Desktop";
      return screenType;
    }
    

    Android YouTube app Play Video Intent

    /**
     * Intent to open a YouTube Video
     * 
     * @param pm
     *            The {@link PackageManager}.
     * @param url
     *            The URL or YouTube video ID.
     * @return the intent to open the YouTube app or Web Browser to play the video
     */
    public static Intent newYouTubeIntent(PackageManager pm, String url) {
        Intent intent;
        if (url.length() == 11) {
            // youtube video id
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
        } else {
            // url to video
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        }
        try {
            if (pm.getPackageInfo("com.google.android.youtube", 0) != null) {
                intent.setPackage("com.google.android.youtube");
            }
        } catch (NameNotFoundException e) {
        }
        return intent;
    }
    

    error: member access into incomplete type : forward declaration of

    Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

    class B;
    
    class A
    {
        void doSomething(B * b);
    };
    
    class B
    {
    public:
        void add() {}
    };
    
    void A::doSomething(B * b)
    {
        b->add();
    }
    

    How to use wait and notify in Java without IllegalMonitorStateException?

    Let's say you have 'black box' application with some class named BlackBoxClass that has method doSomething();.

    Further, you have observer or listener named onResponse(String resp) that will be called by BlackBoxClass after unknown time.

    The flow is simple:

    private String mResponse = null; 
     ...
    BlackBoxClass bbc = new BlackBoxClass();
       bbc.doSomething();
    ...
    @override
    public void onResponse(String resp){        
          mResponse = resp;       
    }
    

    Lets say we don't know what is going on with BlackBoxClass and when we should get answer but you don't want to continue your code till you get answer or in other word get onResponse call. Here enters 'Synchronize helper':

    public class SyncronizeObj {
    public void doWait(long l){
        synchronized(this){
            try {
                this.wait(l);
            } catch(InterruptedException e) {
            }
        }
    }
    
    public void doNotify() {
        synchronized(this) {
            this.notify();
        }
    }
    
    public void doWait() {
        synchronized(this){
            try {
                this.wait();
            } catch(InterruptedException e) {
            }
        }
    }
    }
    

    Now we can implement what we want:

    public class Demo {
    
    private String mResponse = null; 
     ...
    SyncronizeObj sync = new SyncronizeObj();
    
    public void impl(){
    
    BlackBoxClass bbc = new BlackBoxClass();
       bbc.doSomething();
    
       if(mResponse == null){
          sync.doWait();
        }
    
    /** at this momoent you sure that you got response from  BlackBoxClass because
      onResponse method released your 'wait'. In other cases if you don't want wait too      
      long (for example wait data from socket) you can use doWait(time) 
    */ 
    ...
    
    }
    
    
    @override
    public void onResponse(String resp){        
          mResponse = resp;
          sync.doNotify();       
       }
    
    }
    

    How to view DLL functions?

    For native code it's probably best to use Dependency Walker. It also possible to use dumpbin command line utility that comes with Visual Studio.

    CSS Layout - Dynamic width DIV

    This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

    <div style="width:100%;">
        <div style="width: 50px; float: left;">Left Side</div>
        <div style="width: 50px; float: right;">Right Side</div>
        <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
    </div>
    

    Using the "animated circle" in an ImageView while loading stuff

    If you would like to not inflate another view just to indicate progress then do the following:

    1. Create ProgressBar in the same XML layout of the list view.
    2. Make it centered
    3. Give it an id
    4. Attach it to your listview instance variable by calling setEmptyView

    Android will take care the progress bar's visibility.

    For example, in activity_main.xml:

        <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.fcchyd.linkletandroid.MainActivity">
    
        <ListView
            android:id="@+id/list_view_xml"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@color/colorDivider"
            android:dividerHeight="1dp" />
    
       <ProgressBar
            android:id="@+id/loading_progress_xml"
            style="?android:attr/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    
    </RelativeLayout>
    

    And in MainActivity.java:

    package com.fcchyd.linkletandroid;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    public class MainActivity extends AppCompatActivity {
    
    final String debugLogHeader = "Linklet Debug Message";
    Call<Links> call;
    List<Link> arraylistLink;
    ListView linksListV;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        linksListV = (ListView) findViewById(R.id.list_view_xml);
        linksListV.setEmptyView(findViewById(R.id.loading_progress_xml));
        arraylistLink = new ArrayList<>();
    
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.links.linklet.ml")
                .addConverterFactory(GsonConverterFactory
                        .create())
                .build();
    
        HttpsInterface HttpsInterface = retrofit
                .create(HttpsInterface.class);
    
        call = HttpsInterface.httpGETpageNumber(1);
    
        call.enqueue(new Callback<Links>() {
            @Override
            public void onResponse(Call<Links> call, Response<Links> response) {
                try {
                    arraylistLink = response.body().getLinks();
    
                    String[] simpletTitlesArray = new String[arraylistLink.size()];
                    for (int i = 0; i < simpletTitlesArray.length; i++) {
                        simpletTitlesArray[i] = arraylistLink.get(i).getTitle();
                    }
                    ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, simpletTitlesArray);
                    linksListV.setAdapter(simpleAdapter);
                } catch (Exception e) {
                    Log.e("erro", "" + e);
                }
            }
    
            @Override
            public void onFailure(Call<Links> call, Throwable t) {
    
            }
        });
    
    
    }
    

    }

    error LNK2005, already defined?

    Assuming you want 'k' to be a different value in different .cpp files (hence declaring it twice), try changing both files to

    namespace {
        int k;
    }
    

    This guarantees that the name 'k' uniquely identifies 'k' across translation units. The old version static int k; is deprecated.

    If you want them to point to the same value, change one to extern int k;.

    How to get the file extension in PHP?

    This will work as well:

    $array = explode('.', $_FILES['image']['name']);
    $extension = end($array);
    

    Does a `+` in a URL scheme/host/path represent a space?

    • Percent encoding in the path section of a URL is expected to be decoded, but
    • any + characters in the path component is expected to be treated literally.

    To be explicit: + is only a special character in the query component.

    https://tools.ietf.org/html/rfc3986

    Is it possible to decrypt MD5 hashes?

    No, it cannot be done. Either you can use a dictionary, or you can try hashing different values until you get the hash that you are seeking. But it cannot be "decrypted".

    Help needed with Median If in Excel

    Expanding on Brian Camire's Answer:

    Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

    =MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))
    

    Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

    no suitable HttpMessageConverter found for response type

    A refinement of Vadim Zin4uk's answer is just to use the existing GsonHttpMessageConverter class but invoke the setSupportedMediaTypes() setter.

    For spring boot apps, this results into adding to following to your configuration classes:

    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson);
        List<MediaType> supportedMediaTypes = converter.getSupportedMediaTypes();
        if (! supportedMediaTypes.contains(TEXT_PLAIN)) {
            supportedMediaTypes = new ArrayList<>(supportedMediaTypes);
            supportedMediaTypes.add(TEXT_PLAIN);
            converter.setSupportedMediaTypes(supportedMediaTypes);
        }
        return converter;
    }
    

    How to hide reference counts in VS2013?

    Workaround....

    In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

    How to insert a text at the beginning of a file?

    PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.

    I.e., for

    /mnt/Vancouver/Programming/file1
    

    tag the top of file1 with Programming.

    SOLUTION 1 -- non-empty files:

    bn=${PWD##*/}    ## bn: basename
    
    sed -i '1s/^/'"$bn"'\n/' <file>
    

    1s places the text at line 1 of the file.

    SOLUTION 2 -- empty or non-empty files:

    The sed command, above, fails on empty files. Here is a solution, based on https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841

    printf "${PWD##*/}\n" | cat - <file> > temp && mv -f temp <file>
    

    Note that the - in the cat command is required (reads standard input: see man cat for more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp ... See also the explanation at the bottom of http://www.linfo.org/cat.html.

    I also added -f to the mv command, to avoid being asked for confirmations when overwriting files.

    To recurse over a directory:

    for file in *; do printf "${PWD##*/}\n" | cat - $file > temp && mv -f temp $file; done
    

    Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f ... -type solutions) for those.

    ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:

    #!/bin/bash
    
    ## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi
    
    ## To allow spaces in filenames,
    ##   at the top of the script include: IFS=$'\n'; set -f
    ##   at the end of the script include: unset IFS; set +f
    
    IFS=$'\n'; set -f
    
    # ----------------------------------------------------------------------------
    # SET PATHS:
    
    IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/"
    
    # https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command
    
    # FILES=$(find $IN -type f -regex ".*/[0-9]*")        ## recursive; numeric filenames only
    FILES=$(find $IN -type f -regex ".*/[0-9 ]*")         ## recursive; numeric filenames only (may include spaces)
    
    # echo '$FILES:'                                      ## single-quoted, (literally) prints: $FILES:
    # echo "$FILES"                                       ## double-quoted, prints path/, filename (one per line)
    
    # ----------------------------------------------------------------------------
    # MAIN LOOP:
    
    for f in $FILES
    do
    
      # Tag top of file with basename of current dir:
      printf "[top] Tag: ${PWD##*/}\n\n" | cat - $f > temp && mv -f temp $f
    
      # Tag bottom of file with basename of current dir:
      printf "\n[bottom] Tag: ${PWD##*/}\n" >> $f
    done
    
    unset IFS; set +f
    

    How can I multiply and divide using only bit shifting and adding?

    1. A left shift by 1 position is analogous to multiplying by 2. A right shift is analogous to dividing by 2.
    2. You can add in a loop to multiply. By picking the loop variable and the addition variable correctly, you can bound performance. Once you've explored that, you should use Peasant Multiplication

    How do I turn a String into a InputStreamReader in java?

    ByteArrayInputStream also does the trick:

    InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
    

    Then convert to reader:

    InputStreamReader reader = new InputStreamReader(is);
    

    Get paragraph text inside an element

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Where to JavaScript</title>
        <!-- JavaScript in head tag-->
        <script>
            function changeHtmlContent() {
                var content = document.getElementById('content').textContent;
                alert(content);
            }
        </script>
    </head>
    <body>
        <h4 id="content">Welcome to JavaScript!</h4>
        <button onclick="changeHtmlContent()">Change the content</button>
    </body>
    

    Here, we can get the text content of h4 by using:

    document.getElementById('content').textContent
    

    How to create JSON Object using String?

    In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

    https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

    (Android API 19-27. Kotlin 1.2.50)

    What is a word boundary in regex, does \b match hyphen '-'?

    Check out the documentation on boundary conditions:

    http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html

    Check out this sample:

    public static void main(final String[] args)
        {
            String x = "I found the value -12 in my string.";
            System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
        }
    

    When you print it out, notice that the output is this:

    [I found the value -, in my string.]

    This means that the "-" character is not being picked up as being on the boundary of a word because it's not considered a word character. Looks like @brianary kinda beat me to the punch, so he gets an up-vote.

    How to remove the default link color of the html hyperlink 'a' tag?

    This is also possible:

            a {
                all: unset;
            }
    

    unset: This keyword indicates to change all the properties applying to the element or the element's parent to their parent value if they are inheritable or to their initial value if not. unicode-bidi and direction values are not affected.

    Source: Mozilla description of all

    What does the term "Tuple" Mean in Relational Databases?

    tuple = 1 record; n-tuple = ordered list of 'n' records; Elmasri Navathe book (page 198 3rd edition).

    record = either ordered or unordered.

    Regex replace uppercase with lowercase letters

    Try this

    • Find: ([A-Z])([A-Z]+)\b
    • Replace: $1\L$2

    Make sure case sensitivity is on (Alt + C)

    How can I maintain fragment state when added to the back stack?

    first: just use add method instead of replace method of FragmentTransaction class then you have to add secondFragment to stack by addToBackStack method

    second :on back click you have to call popBackStackImmediate()

    Fragment sourceFragment = new SourceFragment ();
    final Fragment secondFragment = new SecondFragment();
    final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
    ft.add(R.id.child_fragment_container, secondFragment );
    ft.hide(sourceFragment );
    ft.addToBackStack(NewsShow.class.getName());
    ft.commit();
                                    
    ((SecondFragment)secondFragment).backFragmentInstanceClick = new SecondFragment.backFragmentNewsResult()
    {
            @Override
            public void backFragmentNewsResult()
            {                                    
                getChildFragmentManager().popBackStackImmediate();                                
            }
    };
    

    Type List vs type ArrayList in Java

    When you write List, you actually tell, that your object implements List interface only, but you don't specify what class your object belongs to.

    When you write ArrayList, you specify that your object class is a resizable-array.

    So, the first version makes your code more flexible in future.

    Look at Java docs:

    Class ArrayList - Resizable-array implementation of the List interface.

    Interface List - An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.

    Array - container object that holds a fixed number of values of a single type.

    Identify if a string is a number

    The best flexible solution with .net built-in function called- char.IsDigit. It works with unlimited long numbers. It will only return true if each character is a numeric number. I used it lot of times with no issues and much easily cleaner solution I ever found. I made a example method.Its ready to use. In addition I added validation for null and empty input. So the method is now totally bulletproof

    public static bool IsNumeric(string strNumber)
        {
            if (string.IsNullOrEmpty(strNumber))
            {
                return false;
            }
            else
            {
                int numberOfChar = strNumber.Count();
                if (numberOfChar > 0)
                {
                    bool r = strNumber.All(char.IsDigit);
                    return r;
                }
                else
                {
                    return false;
                }
            }
        }
    

    Any shortcut to initialize all array elements to zero?

    Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.

    jQuery selector for the label of a checkbox

    $("label[for='"+$(this).attr("id")+"']");
    

    This should allow you to select labels for all the fields in a loop as well. All you need to ensure is your labels should say for='FIELD' where FIELD is the id of the field for which this label is being defined.

    Calculating sum of repeated elements in AngularJS ng-repeat

    After reading all the answers here - how to summarize grouped information, i decided to skip it all and just loaded one of the SQL javascript libraries. I'm using alasql, yeah it takes a few secs longer on load time but saves countless time in coding and debugging, Now to group and sum() I just use,

    $scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);
    

    I know this sounds like a bit of a rant on angular/js but really SQL solved this 30+ years ago and we shouldn't have to re-invent it within a browser.

    Radio button validation in javascript

    <form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">
    
        <div class="text-input">
            <label>Gender: </label>
            <input class="form-control" type="radio" name="gender" id="male" value="male" />
            <label for="male">Male</label>
            <input class="form-control" type="radio" name="gender" id="female" value="female" />
            <label for="female">Female</label>
        </div>
        <div class="text-input" align="center">
            <input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
        </div>
    
    </form>
    
    <script type="text/javascript">
        function radioValidation(){
    
            var gender = document.getElementsByName('gender');
            var genValue = false;
    
            for(var i=0; i<gender.length;i++){
                if(gender[i].checked == true){
                    genValue = true;    
                }
            }
            if(!genValue){
                alert("Please Choose the gender");
                return false;
            }
    
        }
    </script>
    

    Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html

    Escaping single quotes in JavaScript string for JavaScript evaluation

    The thing is that .replace() does not modify the string itself, so you should write something like:

    strInputString = strInputString.replace(...
    

    It also seems like you're not doing character escaping correctly. The following worked for me:

    strInputString = strInputString.replace(/'/g, "\\'");
    

    How to run a program automatically as admin on Windows 7 at startup?

    You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.

    This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.

    I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.

    From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:

    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <RegistrationInfo>
        <Date>2015-01-27T18:30:34</Date>
        <Author>Pete</Author>
      </RegistrationInfo>
      <Triggers>
        <LogonTrigger>
          <StartBoundary>2015-01-27T18:30:00</StartBoundary>
          <Enabled>true</Enabled>
        </LogonTrigger>
      </Triggers>
      <Principals>
        <Principal id="Author">
          <UserId>CHUMBAWUMBA\Pete</UserId>
          <LogonType>InteractiveToken</LogonType>
          <RunLevel>HighestAvailable</RunLevel>
        </Principal>
      </Principals>
      <Settings>
        <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
        <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
        <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
        <AllowHardTerminate>true</AllowHardTerminate>
        <StartWhenAvailable>false</StartWhenAvailable>
        <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
        <IdleSettings>
          <StopOnIdleEnd>true</StopOnIdleEnd>
          <RestartOnIdle>false</RestartOnIdle>
        </IdleSettings>
        <AllowStartOnDemand>true</AllowStartOnDemand>
        <Enabled>true</Enabled>
        <Hidden>false</Hidden>
        <RunOnlyIfIdle>false</RunOnlyIfIdle>
        <WakeToRun>false</WakeToRun>
        <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
        <Priority>7</Priority>
      </Settings>
      <Actions Context="Author">
        <Exec>
          <Command>"c:\windows\system32\notepad.exe"</Command>
        </Exec>
      </Actions>
    </Task>
    

    and it's registered by an administrator command prompt using:

    schtasks /create /tn "start notepad on login" /xml startnotepad.xml
    

    this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.

    How to pip install a package with min and max version range?

    you can also use:

    pip install package==0.5.*
    

    which is more consistent and easy to read.

    Javascript "Not a Constructor" Exception while creating objects

    To add to @wprl's answer, the ES6 object method shorthand, like the arrow functions, cannot be used as a constructor either.

    const o = {
      a: () => {},
      b() {},
      c: function () {}
    };
    
    const { a, b, c } = o;
    
    new a(); // throws "a is not a constructor"
    new b(); // throws "b is not a constructor"
    new c(); // works
    

    urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

    Solution for Anaconda

    My setup is Anaconda Python 3.7 on MacOS with a proxy. The paths are different.

    • This is how you get the correct certificates path:
    import ssl
    ssl.get_default_verify_paths()
    

    which on my system produced

    Out[35]: DefaultVerifyPaths(cafile='/miniconda3/ssl/cert.pem', capath=None,
     openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/miniconda3/ssl/cert.pem',
     openssl_capath_env='SSL_CERT_DIR', openssl_capath='/miniconda3/ssl/certs')
    

    Once you know where the certificate goes, then you concatenate the certificate used by the proxy to the end of that file.

    I had already set up conda to work with my proxy, by running:

    conda config --set ssl_verify <pathToYourFile>.crt
    

    If you don't remember where your cert is, you can find it in ~/.condarc:

    ssl_verify: <pathToYourFile>.crt
    

    Now concatenate that file to the end of /miniconda3/ssl/cert.pem and requests should work, and in particular sklearn.datasets and similar tools should work.

    Further Caveats

    The other solutions did not work because the Anaconda setup is slightly different:

    • The path Applications/Python\ 3.X simply doesn't exist.

    • The path provided by the commands below is the WRONG path

    from requests.utils import DEFAULT_CA_BUNDLE_PATH
    DEFAULT_CA_BUNDLE_PATH
    

    How to detect escape key press with pure JS or jQuery?

    pure JS (no JQuery)

    document.addEventListener('keydown', function(e) {
        if(e.keyCode == 27){
          //add your code here
        }
    });
    

    How to get number of video views with YouTube API?

    Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API

    //Define a constant so that the API KEY can be used globally across the application    
    define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
    
    function youtube_video_statistics($video_id) {
        $json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
        $jsonData = json_decode($json);
        $views = $jsonData->items[0]->statistics->viewCount;
        return $views;
    }
    
    //Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
    echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
    

    I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.

    Certificate is trusted by PC but not by Android

    I had a similar problem and wrote a detailed article about it. If anyone has the same problem, feel free to read my article.

    https://developer-blog.net/administration/ssl-zertifikat-installieren/

    It is a detailed problem description in German language.

    python: get directory two levels up

    Personally, I find that using the os module is the easiest method as outlined below. If you are only going up one level, replace ('../..') with ('..').

        import os
        os.chdir('../..')
    
    --Check:
        os.getcwd()
    

    access denied for user @ 'localhost' to database ''

    You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

    How do I disable Git Credential Manager for Windows?

    If you notice the credential manager UI popping up when you use a JetBrains IDE (such as IntelliJ IDEA, PhpStorm, WebStorm, PyCharm, Rider, RubyMine, Android Studio, or Goland), do this:

    1. In your IDE, go to File | Settings | Version Control | Git.

    2. Disable Use credential helper: Disable "Use credential helper"

    3. Don't forget to press Save.

    Setting onClickListener for the Drawable right of an EditText

    I know this is quite old, but I recently had to do something very similar, and came up with a much simpler solution.

    It boils down to the following steps:

    1. Create an XML layout that contains the EditText and Image
    2. Subclass FrameLayout and inflate the XML layout
    3. Add code for the click listener and any other behavior you want... without having to worry about positions of the click or any other messy code.

    See this post for the full example: Handling click events on a drawable within an EditText

    how to install Lex and Yacc in Ubuntu?

    Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

    sudo apt-get install bison flex
    

    There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

    Spring Boot and multiple external configuration files

    I've just had a similar problem to this and finally figured out the cause: the application.properties file had the wrong ownership and rwx attributes. So when tomcat started up the application.properties file was in the right location, but owned by another user:

    $ chmod 766 application.properties
    
    $ chown tomcat application.properties
    

    PHP: Call to undefined function: simplexml_load_string()

    To fix this error on Centos 7:

    1. Install PHP extension:

      sudo yum install php-xml

    2. Restart your web server. In my case it's php-fpm:

      services php-fpm restart

    contenteditable change events

    I have modified lawwantsin 's answer like so and this works for me. I use the keyup event instead of keypress which works great.

    $('#editor').on('focus', function() {
      before = $(this).html();
    }).on('blur keyup paste', function() { 
      if (before != $(this).html()) { $(this).trigger('change'); }
    });
    
    $('#editor').on('change', function() {alert('changed')});
    

    What is a .pid file and what does it contain?

    The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill

    running multiple bash commands with subprocess

    Join commands with "&&".

    os.system('echo a > outputa.txt && echo b > outputb.txt')
    

    xxxxxx.exe is not a valid Win32 application

    While seleted answer was right time ago, and then noelicus gave correct update regarding v110_xp platform toolset, there is still one more issue that could produse this behaviour.

    A note about issue was already posted by mahesh in his comment, and I would like to highlight this as I have spend couple of days struggling and then find it by myself.

    So, if you have a blank in "Configuration Properties -> Linker -> System -> Subsystem" you will still get the "not valid Win32 app" error on XP and Win2003 while on Win7 it works without this annoying error. The error gone as soon as I've put subsystem:console.

    How to get a variable value if variable name is stored as string?

    For my fellow zsh users, the way to accomplish the same thing as the accepted answer is to use:

    ${(P)a}

    It is appropriately called Parameter name replacement

    This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate. Note that flags set with one of the typeset family of commands (in particular case transformations) are not applied to the value of name used in this fashion.

    If used with a nested parameter or command substitution, the result of that will be taken as a parameter name in the same way. For example, if you have ‘foo=bar’ and ‘bar=baz’, the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be expanded to ‘baz’.

    Likewise, if the reference is itself nested, the expression with the flag is treated as if it were directly replaced by the parameter name. It is an error if this nested substitution produces an array with more than one word. For example, if ‘name=assoc’ where the parameter assoc is an associative array, then ‘${${(P)name}[elt]}’ refers to the element of the associative subscripted ‘elt’.

    java.util.Date and getYear()

    This behavior is documented in the java.util.Date -class documentation:

    Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

    It is also marked as deprecated. Use java.util.Calendar instead.

    How correctly produce JSON by RESTful web service?

    Use this annotation

    @RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
    

    Update Top 1 record in table sql server

    WITH UpdateList_view AS (
      SELECT TOP 1  * from TX_Master_PCBA 
      WHERE SERIAL_NO IN ('0500030309') 
      ORDER BY TIMESTAMP2 DESC 
    )
    
    update UpdateList_view 
    set TIMESTAMP2 = '2013-12-12 15:40:31.593'
    

    jQuery issue in Internet Explorer 8

    jQuery is not being loaded, this is not likely specific to IE8. Check the path on your jQuery include. statement. Or better yet, use the following to the CDN:

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js">
    </script>
    

    Uncaught TypeError: Cannot read property 'msie' of undefined

    $.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

    Removing double quotes from a string in Java

    You can just go for String replace method.-

    line1 = line1.replace("\"", "");
    

    How to upgrade safely php version in wamp server

    To add to the above answer (do steps 1-5).

    1. Click on WAMP -> Select PHP -> Versions: Select the new version installed
    2. Check that your PATH folder is updated to new path to PHP so your OS has same PHP version of WAMP.

    How to merge a transparent png image with another image using PIL

    Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.

    import Image
    
    def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
        fg_img_trans = Image.new("RGBA",fg_img.size)
        fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
        bg_img.paste(fg_img_trans,box,fg_img_trans)
        return bg_img
    
    bg_img = Image.open("bg.png")
    fg_img = Image.open("fg.png")
    p = trans_paste(fg_img,bg_img,.7,(250,100))
    p.show()
    

    Ubuntu: OpenJDK 8 - Unable to locate package

    I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:

    sudo apt-get install debian-keyring debian-archive-keyring

    Make /etc/apt/sources.list.d/debian-jessie-backports.list:

    deb http://httpredir.debian.org/debian/ jessie-backports main
    

    Make /etc/apt/preferences.d/debian-jessie-backports:

    Package: *
    Pin: release o=Debian,a=jessie-backports
    Pin-Priority: -200
    

    Then finally do the install:

    sudo apt-get update
    sudo apt-get -t jessie-backports install openjdk-8-jdk
    

    Adding an onclick event to a table row

    My table is in another iframe so i modified SolutionYogi answer to work with that:

    <script type="text/javascript">
    window.onload = addRowHandlers;
    function addRowHandlers() {
        var iframe = document.getElementById('myiframe');
        var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
    
        var table = innerDoc.getElementById("mytable");
        var rows = table.getElementsByTagName("tr");
        for (i = 0; i < rows.length; i++) {
            var currentRow = table.rows[i];
            var createClickHandler = 
                function(row) 
                {
                    return function() { 
                                            var cell = row.getElementsByTagName("td")[0];
                                            var id = cell.innerHTML;
                                            alert("id:" + id);
                                     };
                }
    
            currentRow.onclick = createClickHandler(currentRow);
        }
    }
    </script>
    

    Where is the Java SDK folder in my computer? Ubuntu 12.04

    WAY-1 : Updated for the shortest and easy way

    Below command will give you the path, But it will only work if java command is working in other words if java path is configured.

    readlink -f $(which java) 
    

    Read more at Where can I find the Java SDK in Linux?


    WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.

    You need to dig into symbolic links. Below is steps to get Java directory

    Step 1:

    $ whereis java
    java: /usr/bin/java /etc/java /usr/share/java
    

    That tells the command java resides in /usr/bin/java.

    Dig again:

    Step 2:

    $ ls -l /usr/bin/java
    lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java
    

    So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java.

    Dig deeper using the same method above:

    Step 3:

    $ ls -l /etc/alternatives/java
    lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java
    

    So, thats the actual location of java: /usr/local/jre.....

    You could still dig deeper to find other symbolic links.


    Reference : where is java's home dir?

    What are SP (stack) and LR in ARM?

    LR is link register used to hold the return address for a function call.

    SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

    From the ARM architecture reference:

    SP, the Stack Pointer

    Register R13 is used as a pointer to the active stack.

    In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

    LR, the Link Register

    Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

    When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

    • Return with a BX LR instruction.

    • On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

    This link gives an example of a trivial subroutine.

    Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

    Changing width property of a :before css selector using JQuery

    Pseudo elements are part of the shadow DOM and can not be modified (but can have their values queried).

    However, sometimes you can get around that by using classes, for example.

    jQuery

    $('#element').addClass('some-class');
    

    CSS

    .some-class:before {
        /* change your properties here */
    }
    

    This may not be suitable for your query, but it does demonstrate you can achieve this pattern sometimes.

    To get a pseudo element's value, try some code like...

    var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
      .getPropertyValue('content')
    

    Clear contents of cells in VBA using column reference

    For anyone like me who came across this and needs a solution that doesn't clear headers, here is the one liner that works for me:

    ActiveSheet.Range("A3:A" & Range("A3").End(xlDown).Row).ClearContents
    

    Starts on the third row - change to your liking.

    Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

    According to the MDN reference page, includes is not supported on Internet Explorer. The simplest alternative is to use indexOf, like this:

    if(window.location.hash.indexOf("?") >= 0) {
        ...
    }
    

    int object is not iterable?

    for .. in statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.

    Opening the Settings app from another app

    Swift 3:

    guard let url = URL(string: UIApplicationOpenSettingsURLString) else {return}
    if #available(iOS 10.0, *) {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
      // Fallback on earlier versions
      UIApplication.shared.openURL(url)
    }
    

    Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

    Only add Any iOS Simulator SDK -> x86_64 to Project's Build Settings -> VALID_ARCHS works for me.

    Xcode version: 12.1 (12A7403)

    enter image description here

    If your project includes some frameworks that don't support x86_64.

    • You can add these framework names(xxx.framework) to Target -> Build Settings -> Excluded Source File Names -> Debug -> Any iOS Simulator SDK.
    • And then modify the Framework Search Paths to delete the paths of these frameworks for Debug -> Any iOS Simulator SDK.

    These two settings can avoid Xcode to build and link these frameworks on simulator mode.

    enter image description here

    enter image description here