Programs & Examples On #Reset button

Calling javascript function in iframe



to access the Reset function in the iframe

document.getElementById("resultFrame") will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

Also see HERE in particular the answer from bobince.

Scroll to element on click in Angular 4

You could do it like this:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

and then in your component:

scroll(el: HTMLElement) {

Edit: I see comments stating that this no longer works due to the element being undefined. I created a StackBlitz example in Angular 7 and it still works. Can someone please provide an example where it does not work?

What is the easiest way to remove the first character from a string?

For example : a = "One Two Three"

1.9.2-p290 > a = "One Two Three"
 => "One Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "ne Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "e Two Three" 

1.9.2-p290 > a = a[1..-1]
 => " Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "wo Three" 

In this way you can remove one by one first character of the string.

SQLite with encryption/password protection

SQLite has hooks built-in for encryption which are not used in the normal distribution, but here are a few implementations I know of:

  • SEE - The official implementation.
  • wxSQLite - A wxWidgets style C++ wrapper that also implements SQLite's encryption.
  • SQLCipher - Uses openSSL's libcrypto to implement.
  • SQLiteCrypt - Custom implementation, modified API.
  • botansqlite3 - botansqlite3 is an encryption codec for SQLite3 that can use any algorithms in Botan for encryption.
  • sqleet - another encryption implementation, using ChaCha20/Poly1305 primitives. Note that wxSQLite mentioned above can use this as a crypto provider.

The SEE and SQLiteCrypt require the purchase of a license.

Disclosure: I created botansqlite3.

Change color and appearance of drop down arrow

Try changing the color of your "border-top" attribute to white

How to JOIN three tables in Codeigniter

   Check bellow code it`s working fine and  common model function also 
    supported more then one join and also supported  multiple where condition

   //put bellow code in your controller

    $album_id='';//album id 

   //pass join table value in bellow format
    $join_str[0]['table'] = 'Category';
    $join_str[0]['join_table_id'] = 'Category.cat_id';
    $join_str[0]['from_table_id'] = 'Album.cat_id';
    $join_str[0]['join_type'] = 'left';

    $join_str[1]['table'] = 'Soundtrack';
    $join_str[1]['join_table_id'] = 'Soundtrack.album_id';
    $join_str[1]['from_table_id'] = 'Album.album_id';
    $join_str[1]['join_type'] = 'left';

    $selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";

   $albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
                               //call common model function

    if (!empty($albumData)) {
        print_r($albumData); // print album data

    //put bellow code in your common model file

   function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
    //if join_str array is not empty then implement the join query
    if (!empty($join_str)) {
        foreach ($join_str as $join) {
            if ($join['join_type'] == '') {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
            } else {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);

    //condition array pass to where condition

    //Setting Limit for Paging
    if ($limit != '' && $offset == 0) {
    } else if ($limit != '' && $offset != 0) {
        $this->db->limit($limit, $offset);
    //order by query
    if ($sortby != '' && $orderby != '') {
        $this->db->order_by($sortby, $orderby);

    $query = $this->db->get($tablename);
    //if limit is empty then returns total count
    if ($limit == '') {
    //if limit is not empty then return result array
    return $query->result_array();

Unzip All Files In A Directory

In any POSIX shell, this will unzip into a different directory for each zip file:

for file in *.zip
    unzip "$file" -d "$directory"

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

Bit reversal in pseudo code

source -> byte to be reversed b00101100 destination -> reversed, also needs to be of unsigned type so sign bit is not propogated down

copy into temp so original is unaffected, also needs to be of unsigned type so that sign bit is not shifted in automaticaly

bytecopy = b0010110

LOOP8: //do this 8 times test if bytecopy is < 0 (negative)

    set bit8 (msb) of reversed = reversed | b10000000 

else do not set bit8

shift bytecopy left 1 place
bytecopy = bytecopy << 1 = b0101100 result

shift result right 1 place
reversed = reversed >> 1 = b00000000
8 times no then up^ LOOP8
8 times yes then done.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is what I do:

Uri selectedImageURI = data.getData();    imageFile = new File(getRealPathFromURI(selectedImageURI)); 

private String getRealPathFromURI(Uri contentURI) {
  Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
  if (cursor == null) { // Source is Dropbox or other similar local file path
      return contentURI.getPath();
      } else { 
      int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
      return cursor.getString(idx); 

NOTE: managedQuery() method is deprecated, so I am not using it.

This answer is from m3n0R on question android get real path by Uri.getPath() and I claim no credit. I just thought that people who haven't solved this issue yet could use this.

How long is the SHA256 hash?

Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.

len() of a numpy array in python

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

Update Eclipse with Android development tools v. 23

For me it helped to delete Android 4.4W which is also API 20 and might be a cause for the conflict. So only install Android 4.4W or Android L until they fix it.

And (again this might only be for me) it only works in Android Studio not in Eclipse ...

Export to CSV via PHP

I personally use this function to create CSV content from any array.

function array2csv(array &$array)
   if (count($array) == 0) {
     return null;
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   return ob_get_clean();

Then you can make your user download that file using something like:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");

Usage example:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);

How to convert milliseconds to "hh:mm:ss" format?

I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:

import static java.util.concurrent.TimeUnit.*


private static String formatElapsedTime(long millis) {

    int hrs = MILLISECONDS.toHours(millis) % 24
    int min = MILLISECONDS.toMinutes(millis) % 60
    int sec = MILLISECONDS.toSeconds(millis) % 60
    int mls = millis % 1000

    sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])

Safely override C++ virtual functions

In MSVC++ you can use keyword override

class child : public parent {
  virtual void handle_event(int something) <b>override</b> {
    // new exciting code

override works both for native and CLR code in MSVC++.

Observable Finally on Subscribe

I'm now using RxJS 5.5.7 in an Angular application and using finalize operator has a weird behavior for my use case since is fired before success or error callbacks.

Simple example:

// Simulate an AJAX callback...
    finalize(() => {
      // Do some work after complete...
      console.log('Finalize method executed before "Data available" (or error thrown)');
      response => {
        console.log('Data available.');
      err => {

I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

Simple example:

// Simulate an AJAX callback...
      response => {
        console.log('Data available.');
      err => {
  .add(() => {
    // Do some work after complete...
    console.log('At this point the success or error callbacks has been completed.');

Extracting the last n characters from a string in R

A little modification on @Andrie solution gives also the complement:

substrR <- function(x, n) { 
  if(n > 0) substr(x, (nchar(x)-n+1), nchar(x)) else substr(x, 1, (nchar(x)+n))
x <- "moSvmC20F.5.rda"
[1] "moSvmC20F.5"

That was what I was looking for. And it invites to the left side:

substrL <- function(x, n){ 
  if(n > 0) substr(x, 1, n) else substr(x, -n+1, nchar(x))
[1] "SvmC20F.5"

How to chain scope queries with OR instead of AND?

This is a very convenient way and it works fine in Rails 5:

  .where(transaction_type: ["Create", "Correspond"])
      transaction_type: "Status",
      field: "Status",
      newvalue: ["resolved", "deleted"]
    Transaction.where(transaction_type: "Set", field: "Queue")

How is returning the output of a function different from printing it?

Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.

I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.

return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user. Consider these two programs:

def function_that_prints():
    print "I printed"

def function_that_returns():
    return "I returned"

f1 = function_that_prints()
f2 = function_that_returns()

print "Now let us see what the values of f1 and f2 are"

print f1 --->None

print f2---->"I returned"

When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.

When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"

SQL Not Like Statement not working

I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;

Instead of;




Basically moving the "NOT" the other side of the field I was evaluating worked for me.

How to turn NaN from parseInt into 0 for an empty string?

function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5

How to retrieve GET parameters from JavaScript

tl;dr solution on a single line of code using vanilla JavaScript

var queryDict = {}"&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

This is the simplest solution. It unfortunately does not handle multi-valued keys and encoded characters.

> queryDict
a: "%2Fadmin"  // Overridden with the last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined

Multi-valued keys and encoded characters?

See the original answer at How can I get query string values in JavaScript?.

> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, " test.asp?name=ståle&car=saab"]

In your example, you would access the value like this:

> qd.returnurl    // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Including dependencies in a jar with Maven

You can do this using the maven-assembly plugin with the "jar-with-dependencies" descriptor. Here's the relevant chunk from one of our pom.xml's that does this:

      <!-- any other plugins -->

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:


INSERT INTO MyTable(Name, Address, PhoneNo)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

The application may be doing too much work on its main thread

I am not an expert, but I got this debug message when I wanted to send data from my android application to a web server. Though I used AsyncTask class and did the data transfer in background, for getting the result data back from server I used get() method of the AsyncTask class which makes the UI synchronous which means that your UI will be waiting for too long. So my advice is to make your app do every network oriented tasks on a separate thread.

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android=""
    android:background="#ffcc5d00" >





                        android:layout_gravity="center" />


                        android:layout_gravity="center" />



                        android:layout_gravity="center" />


                        android:layout_gravity="center" />

Where can I find "make" program for Mac OS X Lion?

Xcode 5.1 no longer provides command line tools in the Preferences section. You now go to, and select the command line tools version for your OS X release. The installer puts them in /usr/bin.

SQLite add Primary Key

According to the sqlite docs about table creation, using the create table as select produces a new table without constraints and without primary key.

However, the documentation also says that primary keys and unique indexes are logically equivalent (see constraints section):

In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database. (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the following schemas are logically equivalent:



CREATE TABLE t1(a, b);

So, even if you cannot alter your table definition through SQL alter syntax, you can get the same primary key effect through the use an unique index.

Also, any table (except those created without the rowid syntax) have an inner integer column known as "rowid". According to the docs, you can use this inner column to retrieve/modify record tables.

Alternate output format for psql

you can use the zenity to displays the query output as html table.

  • first implement bash script with following code:

    cat > '/tmp/sql.op'; zenity --text-info --html --filename='/tmp/sql.op';

    save it like

  • Then export the environment variable PAGER by set full path of the script as value.

    for example:- export PAGER='/path/'

  • Then login to the psql program then execute the command \H

  • And finally execute any query,the tabled output will displayed in the zenity in html table format.

Find the host name and port using PSQL commands

The postgresql port is defined in your postgresql.conf file.

For me in Ubuntu 14.04 it is: /etc/postgresql/9.3/main/postgresql.conf

Inside there is a line:

port = 5432

Changing the number there requires restart of postgresql for it to take effect.

How to Consume WCF Service with Android

From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.

7-Zip command to create and extract a password-protected ZIP file on Windows?

General Syntax:

7z a archive_name target parameters

Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.


  • -p encrypt and prompt for PW.
  • -pPUT_PASSWORD_HERE (this replaces -p) if you want to preset the PW with no prompt.
  • -mhe=on to hide file structure, otherwise file structure and names will be visible by default.

Eg. This will prompt for a PW and hide file structures:

7z a archive_name target -p -mhe=on

Eg. No prompt, visible file structure:

7z a archive_name target -pPUT_PASSWORD_HERE

And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.

Automatically enter SSH password with script

I am using below solution but for that you have to install sshpass If its not already installed, install it using sudo apt install sshpass

Now you can do this,

sshpass -p *YourPassword* shh root@IP

You can create a bash alias as well so that you don't have to run the whole command again and again. Follow below steps

cd ~

sudo nano .bash_profile

at the end of the file add below code

mymachine() { sshpass -p *YourPassword* shh root@IP }

source .bash_profile

Now just run mymachine command from terminal and you'll enter your machine without password prompt.


  1. mymachine can be any command of your choice.
  2. If security doesn't matter for you here in this task and you just want to automate the work you can use this method.

Is there a combination of "LIKE" and "IN" in SQL?

This works for comma separated values

SELECT ' AND (a.arc_checknum LIKE ''%' + REPLACE(@arc_checknum,',','%'' OR a.arc_checknum LIKE ''%') + '%'')''

Evaluates to:

 AND (a.arc_checknum LIKE '%ABC%' OR a.arc_checknum LIKE '%135%' OR a.arc_checknum LIKE '%MED%' OR a.arc_checknum LIKE '%ASFSDFSF%' OR a.arc_checknum LIKE '%AXX%')

If you want it to use indexes, you must omit the first '%' character.

How to set the part of the text view is clickable

My function for make multiple links inside TextView
Update 2020: Now this function able to support multiple same texts link inside 1 TextView, but remember to put the link in the correct order

fun TextView.makeLinks(vararg links: Pair<String, View.OnClickListener>) {
    val spannableString = SpannableString(this.text)
    var startIndexOfLink = -1
    for (link in links) {
        val clickableSpan = object : ClickableSpan() {
            override fun updateDrawState(textPaint: TextPaint) {
                // use this to change the link color
                textPaint.color = textPaint.linkColor
                // toggle below value to enable/disable
                // the underline shown below the clickable text
                textPaint.isUnderlineText = true

            override fun onClick(view: View) {
                Selection.setSelection((view as TextView).text as Spannable, 0)
        startIndexOfLink = this.text.toString().indexOf(link.first, startIndexOfLink + 1)
//      if(startIndexOfLink == -1) continue // todo if you want to verify your texts contains links text
            clickableSpan, startIndexOfLink, startIndexOfLink + link.first.length,
    this.movementMethod =
        LinkMovementMethod.getInstance() // without LinkMovementMethod, link can not click
    this.setText(spannableString, TextView.BufferType.SPANNABLE)


        Pair("Terms of Service", View.OnClickListener {
            Toast.makeText(applicationContext, "Terms of Service Clicked", Toast.LENGTH_SHORT).show()
        Pair("Privacy Policy", View.OnClickListener {
            Toast.makeText(applicationContext, "Privacy Policy Clicked", Toast.LENGTH_SHORT).show()


    android:text="Please accept Terms of Service and Privacy Policy"
    android:textColorHighlight="#f00" // background color when pressed
    android:textSize="20sp" />



Solution for clear the link highlight selection follow

How to populate/instantiate a C# array with a single value?

Or... you could simply use inverted logic. Let false mean true and vice versa.

Code sample

// bool[] isVisible = Enumerable.Repeat(true, 1000000).ToArray();
bool[] isHidden = new bool[1000000]; // Crazy-fast initialization!

// if (isVisible.All(v => v))
if (isHidden.All(v => !v))
    // Do stuff!

How to list all the files in android phone by using adb shell?

I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try

adb shell ls -R /

You probably need the root permission though.

Edit: As other answers suggest, use ls with grep like this:

adb shell ls -Ral yourDirectory | grep -i yourString


adb shell ls -Ral / | grep -i myfile

-i is for ignore-case. and / is the root directory.

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
     case $OPTION in
             exit 1

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
     exit 1

./ -t test -r server -p password -v

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

VB.NET: Clear DataGridView

When feeding info from an SQL query into a datagridview you can clear the datagridview first before reloading it.

Where I have defined dbDataSet as New DataTable I can do a clear. dbDataSet must be at the start of the form within the Public Class Form

Dim dbDataset AS New DataTable

within the code of you Private Sub, place


Hide scroll bar, but while still being able to scroll

This answer doesn't include the code, so here is the solution from page:

According to the page this approach doesn't need to know the width of the scrollbar ahead of time in order to work and the solution works for all browsers too, and can be seen here.

The good thing is that you are not forced to use padding or width differences to hide the scrollbar.

This is also zoom safe. Padding/width solutions show the scrollbar when zoomed to minimum.

Firefox fix:

.outer-container {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
.outer-container {_x000D_
  border: 5px solid purple;_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
.inner-container {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  overflow-x: hidden;_x000D_
  overflow-y: scroll;_x000D_
  padding-right: 150px;_x000D_
.inner-container::-webkit-scrollbar {_x000D_
  display: none;_x000D_
<div class="outer-container">_x000D_
  <div class="inner-container">_x000D_
    <div class="element">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vehicula quam nibh, eu tristique tellus dignissim quis. Integer condimentum ultrices elit ut mattis. Praesent rhoncus tortor metus, nec pellentesque enim mattis nec. Nulla vitae turpis ut_x000D_
      dui consectetur pellentesque quis vel est. Curabitur rutrum, mauris ut mollis lobortis, sem est congue lectus, ut sodales nunc leo a libero. Cras quis sapien in mi fringilla tempus condimentum quis velit. Aliquam id aliquam arcu. Morbi tristique_x000D_
      aliquam rutrum. Duis tincidunt, orci suscipit cursus molestie, purus nisi pharetra dui, tempor dignissim felis turpis in mi. Vivamus ullamcorper arcu sit amet mauris egestas egestas. Vestibulum turpis neque, condimentum a tincidunt quis, molestie_x000D_
      vel justo. Sed molestie nunc dapibus arcu feugiat, ut sollicitudin metus sagittis. Aliquam a volutpat sem. Quisque id magna ultrices, lobortis dui eget, pretium libero. Curabitur aliquam in ante eu ultricies._x000D_

Add jars to a Spark Job - spark-submit

When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths

Example :

spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar

Set field value with reflection

Hope this is something what you are trying to do :

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {

    private Map ttp = new HashMap(); 

    public  void test() {
        Field declaredField =  null;
        try {

            declaredField = Test.class.getDeclaredField("ttp");
            boolean accessible = declaredField.isAccessible();


            ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
            concHashMap.put("key1", "value1");
            declaredField.set(this, concHashMap);
            Object value = ttp.get("key1");



        } catch (NoSuchFieldException 
                | SecurityException
                | IllegalArgumentException 
                | IllegalAccessException e) {


    public static void main(String... args) {
        Test test = new Test();

It prints :


Batch file to perform start, run, %TEMP% and delete all

Just use

del /f /q C:\Users\%username%\AppData\Local\temp

And it will work.

Note: It will delete the whole folder however, Windows will remake it as it needs.

Pause in Python

Try os.system("pause") — I used it and it worked for me.

Make sure to include import os at the top of your script.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:


Up next is the create script. Creating a database file:


SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);


After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
   // logic

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:


Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Why does modern Perl avoid UTF-8 by default?

We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.

There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".

As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.

If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.


How to validate array in Laravel?

The recommended way to write validation and authorization logic is to put that logic in separate request classes. This way your controller code will remain clean.

You can create a request class by executing php artisan make:request SomeRequest.

In each request class's rules() method define your validation rules:

public function rules()
   return [
    "name"    => [
          'array', // input must be an array
          'min:3'  // there must be three members in the array
    "name.*"  => [
          'string',   // input must be of type string
          'distinct', // members of the array must be unique
          'min:3'     // each string must have min 3 chars

In your controller write your route function like this:

// SomeController.php
public function store(SomeRequest $request) 
  // Request is already validated before reaching this point.
  // Your controller logic goes here.

public function update(SomeRequest $request)
  // It isn't uncommon for the same validation to be required
  // in multiple places in the same controller. A request class
  // can be beneficial in this way.

Each request class comes with pre- and post-validation hooks/methods which can be customized based on business logic and special cases in order to modify the normal behavior of request class.

You may create parent request classes for similar types of requests (e.g. web and api) requests and then encapsulate some common request logic in these parent classes.

Getting number of elements in an iterator in Python

I like the cardinality package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.


>>> import cardinality
>>> cardinality.count([1, 2, 3])
>>> cardinality.count(i for i in range(500))
>>> def gen():
...     yield 'hello'
...     yield 'world'
>>> cardinality.count(gen())

The actual count() implementation is as follows:

def count(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

How to make HTML input tag only accept numerical values?

I have used regular expression to replace the input value with the pattern needed.

var userName = document.querySelector('#numberField');_x000D_
userName.addEventListener('input', restrictNumber);_x000D_
function restrictNumber (e) {  _x000D_
  var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");_x000D_
  this.value = newValue;_x000D_
<input type="text" id="numberField">

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.


will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

How to enable curl in xampp?

It should be available in php.ini file. You need to un-comment the line for curl extension:

  ^----- remove semi-colon

pip3: command not found

You would need to install pip3.

On Linux, the command would be: sudo apt install python3-pip

On Mac, using brew, first brew install python3
Then brew postinstall python3

Try calling pip3 -V to see if it worked.

What does %w(array) mean?

%w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

How can I set the default value for an HTML <select> element?

You just need to put attribute "selected" on a particular option instead direct to select element.

Here is snippet for same and multiple working example with different values.

   Select Option 3 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option selected="selected">3</option>_x000D_
   Select Option 5 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option selected="selected">5</option>_x000D_
   Select Option 2 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option selected="selected">2</option>_x000D_

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?


First find the function:

That contains a link to a time.h, which as a header should be where structs are defined:

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Load CSV data into MySQL in Python

Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.

How to debug in Android Studio using adb over WiFi

I used the following steps to successfully debug over wifi connection. I recommend this solution to everybody experiencing problems using integrated solutions like Android WiFi ADB plugin. In my case it failed to keep the Wifi connection to my device after unplugging USB. The following solution overcomes this problem.

1. Connecting device

a. Connecting device using local wlan

If you have a local wlan you can connect your android device and your pc to this wlan. Then identify the IP address of the android device by looking into its wlan settings.

b. Connecting device directly using a hotspot

I prefer to connect with a hotspot on the device. This is more private and does not open your debugging connection to the (public) wlan.

  1. Create a Wifi hotspot on the Android device
  2. Connect PC to hotspot
  3. On PC look into network connection status of this hotspot connection to find the IPADDRESS of your device.
    My system showed IPADDRESS

2. Create debugging connection

  1. Connect your device to USB.
  2. Issue command adb tcpip 5555 to open a port on the device for adb connection.
  3. Create wireless debugging connection adb connect IPADDRESS.
    In my case the command looked like adb connect

The command adb devices -l should now display two devices if everything is ok. For example:

List of devices attached
ZY2244N2ZZ             device product:athene model:Moto_G__4_ device:athene      device product:athene model:Moto_G__4_ device:athene

3. Keeping debugging connection

The tricky part comes when unplugging the USB connection. In my case both connections are closed immediately! This may not be the case for all users. For me this was the reason that I could not use Android WiFi ADB plugin for android studio. I solved the problem by manually reconnecting the Wifi after unplugging usb by

adb connect

After that adb devices -lshows a single wifi connected device. This devices shows also up in android studio and can then be selected for debugging. When the connection is unstable you may need to repeat the above command from time to time to reactivate the connection.

Google Maps setCenter()

 function resize() {
        var map_obj = document.getElementById("map_canvas");

      /* = "500px"; = "225px";*/
        if (map) {
            map.panTo(new GLatLng(lat,lon));

<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
    End If

Prevent BODY from scrolling when a modal is opened

Sadly none of the answers above fixed my issues.

In my situation, the web page originally has a scroll bar. Whenever I click the modal, the scroll bar won't disappear and the header will move to right a bit.

Then I tried to add .modal-open{overflow:auto;} (which most people recommended). It indeed fixed the issues: the scroll bar appears after I open the modal. However, another side effect comes out which is that "background below the header will move to the left a bit, together with another long bar behind the modal"

Long bar behind modal

Luckily, after I add {padding-right: 0 !important;}, everything is fixed perfectly. Both the header and body background didn't move and the modal still keeps the scrollbar.

Fixed image

Hope this can help those who are still stuck with this issue. Good luck!

add maven repository to build.gradle

Add the maven repository outside the buildscript configuration block of your main build.gradle file as follows:

repositories {
        maven {
            url ""

Make sure that you add them after the following:

apply plugin: ''

Checking if a SQL Server login already exists

Try this (replace 'user' with the actual login name):

SELECT name 
FROM [master].[sys].[syslogins]
WHERE NAME = 'user')

    --create login here

Forbidden You don't have permission to access / on this server

Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use

Require all granted

instead of

Order allow,deny
Allow from all

The Order and Allow directives are deprecated in Apache 2.4.

parse html string with jquery

I'm not a 100% sure, but won't


produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

HTML5 Video Autoplay not working correctly

Working solution October 2018, for videos including audio channel

 $(document).ready(function() {

Have a look at another of mine, more in-depth answer:

How to initialize static variables

In PHP 7.0.1, I was able to define this:

public static $kIdsByActions = array(
  MyClass1::kAction => 0,
  MyClass2::kAction => 1

And then use it like this:


Where can I set path to make.exe on Windows?

here I'm providing solution to setup terraform enviroment variable in windows to beginners.

  1. Download the terraform package from portal either 32/64 bit version.
  2. make a folder in C drive in program files if its 32 bit package you have to create folder inside on programs(x86) folder or else inside programs(64 bit) folder.
  3. Extract a downloaded file in this location or copy terraform.exe file into this folder. copy this path location like C:\Programfile\terraform\
  4. Then got to Control Panel -> System -> System settings -> Environment Variables

Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\

and Save it.

  1. Open new terminal and now check the terraform.

Error:java: javacTask: source release 8 requires target release 1.8

I fixed it by modify my POM file. Notice the last comment under the highest voted answer.


The source must matches the target.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

When and why do I need to use cin.ignore() in C++?

When you want to throw away a specific number of characters from the input stream manually.

A very common use case is using this to safely ignore newline characters since cin will sometimes leave newline characters that you will have to go over to get to the next line of input.

Long story short it gives you flexibility when handling stream input.

How do I disable Git Credential Manager for Windows?

I was able to uninstall the Git Credential Manager for Windows using the uninstall option:

git-credential-manager.exe uninstall

Run this command in C:\Program Files\Git\mingw64\libexec\git-core

How to search a Git repository by commit message?

Though a bit late, there is :/ which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/, e.g.:

git show :/keyword(s)

Here <keywords> can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:

git log -1 -p ":/a few words"

Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:

git show 'HEAD^{/fix nasty bug}'

See: git revisions manual.

What is the best workaround for the WCF client `using` block issue?

Use an extension method:

public static class CommunicationObjectExtensions
    public static TResult MakeSafeServiceCall<TResult, TService>(this TService client, Func<TService, TResult> method) where TService : ICommunicationObject
        TResult result;

            result = method(client);
            catch (CommunicationException)
                client.Abort(); // Don't care about these exceptions. The call has completed anyway.
            catch (TimeoutException)
                client.Abort(); // Don't care about these exceptions. The call has completed anyway.
            catch (Exception)

        return result;

Eclipse CDT: Symbol 'cout' could not be resolved

You guys are looking under the wrong section. I realized the difference when I installed in Linux after recently getting frustrated with Windows and the difference was immediately apparent.

In the new setup I have an includes folder in a projected that I created out of existing source. I can expand this and see a ton of includes; however, I cannot add to them. This lead me to a hunt for where these files were being listed.

They're listed under the Project Properties > C/C++ General > Preprocessor Includes > GNU C++ CDT GCC Built-in Compiler Settings [Shared] Under that is a ton of includes.

These settings are set by the toolchain you've selected.

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

Normalizing a list of numbers in Python

How long is the list you're going to normalize?

def psum(it):
    "This function makes explicit how many calls to sum() are done."
    print "Another call!"
    return sum(it)

raw = [0.07,0.14,0.07]
print "How many calls to sum()?"
print [ r/psum(raw) for r in raw]

print "\nAnd now?"
s = psum(raw)
print [ r/s for r in raw]

# if one doesn't want auxiliary variables, it can be done inside
# a list comprehension, but in my opinion it's quite Baroque    
print "\nAnd now?"
print [ r/s  for s in [psum(raw)] for r in raw]


# How many calls to sum()?
# Another call!
# Another call!
# Another call!
# [0.25, 0.5, 0.25]
# And now?
# Another call!
# [0.25, 0.5, 0.25]
# And now?
# Another call!
# [0.25, 0.5, 0.25]

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle:


Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:


    <script type='text/javascript' src='//'></script>

    <script type='text/javascript'>
      //Your script.


Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

mysql: SOURCE error 2?

May be the file name or path you are used may be incorrect

In my system i created file abcd.sql at c:\

and used command mysql> source c:\abcd.sql Then i got result

Save PL/pgSQL output from PostgreSQL to a CSV file

Do you want the resulting file on the server, or on the client?

Server side

If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;

This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

  1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
  2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.

Client side

The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

\copy (Select * From foo) To '/tmp/test.csv' With CSV

Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

From the docs:

Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Get docker container id from container name

Docker image inspect ImageName\ImageId --format={{'.ConatinerConfig.Hostname'}}

RadioGroup: How to check programmatically

Grab the radio group and look at the children to see if any are unchecked.

RadioGroup rg = (RadioGroup) view;
int checked = savedInstanceState.getInt(wrap.getAttributeName());

if(checked != -1) {
    RadioButton btn = (RadioButton) rg.getChildAt(checked);

IE7 Z-Index Layering Issues

I encountered this issue, but on a large project where HTML changes had to be requested and became a whole issue, so I was looking for a pure css solution.

By placing position:relative; z-index:-1 on my main body content my header drop down content suddenly displayed above the body content in ie7 (it was already displaying without issue in all other browsers and in ie8+)

The problem with that was then this disabled all hover and click actions on all content in the element with the z-index:-1 so i went to the parent element of the whole page and gave it a position:relative; z-index:1

Which fixed the issue and retained the correct layering functionality.

Feels a bit hacky, but worked as required.

C# - Print dictionary

More cleaner way using LINQ

var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);

On select change, get data attribute value

document.querySelector('select').onchange = function(){   

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

Send json post using php

You can use CURL for this purpose see the example code:

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));


$response = json_decode($json_response, true);

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that using the @EnableAutoConfiguration annotation on a test class won't work if you are using @SpringApplicationConfiguration to load your Application class. The thing is that you already have a @EnableAutoConfiguration annotation in the Application class that does not exclude the CrshAutoConfiguration.Spring uses that annotation instead of the one on your test class to do the auto configuration of your beans.

I think that your best bet is to use a different application context for your tests and exclude the CrshAutoConfiguration in that class.

I did some tests and it seems that @EnableAutoConfiguration on the test class is completely ignore if you are using the @SpringApplicationConfiguration annotation and the SpringJUnit4ClassRunner.

What is middleware exactly?

it is a software layer between the operating system and applications on each side of a distributed computing system in a network. In fact it connects heterogeneous network and software systems.

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

Make $JAVA_HOME easily changable in Ubuntu

Put the environment variables into the global /etc/environment file:

export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.

check if array is empty (vba excel)

Adding into this: it depends on what your array is defined as. Consider:

dim a() as integer
dim b() as string
dim c() as variant

'these doesn't work
if isempty(a) then msgbox "integer arrays can be empty"
if isempty(b) then msgbox "string arrays can be empty"

'this is because isempty can only be tested on classes which have an .empty property

'this do work
if isempty(c) then msgbox "variants can be empty"

So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example

dim a() as integer
dim bEmpty as boolean


on error resume next
bempty=not isnumeric(ubound(a))
on error goto 0

But this is really clumsy... A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it's a variable declared at the same time, if it loses it's value, then you know that you need to reinitialise your array. However, if it is initialised, then all you're doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you're going to be needing to check it often.

option explicit

'declared at module level
dim a() as integer
dim aInitialised as boolean

sub DoSomethingWithA()
if not aInitialised then InitialiseA
'you can now proceed confident that a() is intialised
end sub

sub InitialiseA()
'insert code to do whatever is required to initialise A
redim a(10)
end sub

The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.

function isInitialised(byref a() as variant) as boolean
on error resume next
end function

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll


depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

How do I write data to csv file in columns and rows from a list in python?

import pandas as pd
for i in range(len(doc_list)):

Using pandas dataframe,we can write to csv. First create a dataframe as per the your needs for storing in csv. Then create csv of the dataframe using pd.DataFrame.to_csv() API.

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

How to add a “readonly” attribute to an <input>?

Check the code below:

<input id="mail">


 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again


How to get the selected index of a RadioGroup in Android

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;

were not worked well in the chrome browse.

C# Convert a Base64 -> byte[]

I've written an extension method for this purpose:

public static byte[] FromBase64Bytes(this byte[] base64Bytes)
    string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
    return Convert.FromBase64String(base64String);

Call it like this:

byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();

I hope it helps someone.

jQuery Validate - Enable validation for hidden fields

The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.

To fix this I added the following to manually trigger the jquery validation event that gets added by the library:

$(".chosen-select").each(function() {
  $(this).chosen().on("change", function() {

jquery.validate will now add the .valid class to the underlying select list.

Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group, and each input has .form-control.

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        AssetID = x.AssetID,
        Status = xx.Online ?? false

Insert images to XML file

Here's some code taken from Kirk Evans Blog that demonstrates how to encode an image in C#;

//Load the picture from a file
Image picture = Image.FromFile(@"c:\temp\test.gif");

//Create an in-memory stream to hold the picture's bytes
System.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();
picture.Save(pictureAsStream, System.Drawing.Imaging.ImageFormat.Gif);

//Rewind the stream back to the beginning
pictureAsStream.Position = 0;
//Get the stream as an array of bytes
byte[] pictureAsBytes = pictureAsStream.ToArray();

//Create an XmlTextWriter to write the XML somewhere... here, I just chose
//to stream out to the Console output stream
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);

//Write the root element of the XML document and the base64 encoded data
writer.WriteStartElement("w", "binData",

writer.WriteBase64(pictureAsBytes, 0, pictureAsBytes.Length);


How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Add an object to a python list

You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:



>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

I did the following to resolve mine:

  1. Open VirtualBox and check the new machine that is created for you by GenyMotion
  2. Right Click on it and choose Settings then go to the Network section/tab
  3. In Adapter 1 tab, It should be attached to Host-Only Adapter. Check what is the name of the used adapter Name then close it.

  4. Open File|Preferences in Virtualbox, then go to Network section/tab

  5. Under Host-only Networks tab, find the same name you have already gotten in step 3.

  6. Double click on that name and apple the following configuration

    • Adapter Tab:
    • IPv4 Adapter:
    • IPV4 Network Mask:

    • DHCP Server:

    • Check "Enable Server"
    • Server Address:
    • Server Mask:
    • Lower Address Bound:
    • Higher Address Bound:

Cause of a process being a deadlock victim

Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.

How do I lock the orientation to portrait mode in a iPhone Web Application?

You can specify CSS styles based on viewport orientation: Target the browser with body[orient="landscape"] or body[orient="portrait"]


Apple's approach to this issue is to allow the developer to change the CSS based on the orientation change but not to prevent re-orientation completely. I found a similar question elsewhere:

Remove Array Value By index in jquery

Your example code is wrong and will throw a SyntaxError. You seem to have confused the syntax of creating an object Object with creating an Array.

The correct syntax would be: var arr = [ "abc", "def", "ghi" ];

To remove an item from the array, based on its value, use the splice method:

arr.splice(arr.indexOf("def"), 1);

To remove it by index, just refer directly to it:

arr.splice(1, 1);

Selenium WebDriver findElement(By.xpath()) not working for me

You can use contains too:

element = findElement(By.xpath("//input[contains (@test-id,"test-username")]");

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

1) In some cases, yes. If the WSDL contains things like Policies and such that direct the runtime behavior, then the WSDL may be required at runtime. Artifacts are not generated for policy related things and such. Also, in some obscure RPC/Literal cases, not all the namespaces that are needed are output in the generated code (per spec). Thus, the wsdl would be needed for them. Obscure cases though.

2) I thought something like would work. What version of CXF? That sounds like a bug. You can try an empty string in there (just spaces). Not sure if that works or not. That said, in your code, you can use the constructor that takes the WSDL URL and just pass null. The wsdl wouldn't be used.

3) Just the limitations above.

Center a popup window on screen?

It works very well in Firefox.
Just change the top variable to any other name and try again

        var w = 200;
        var h = 200;
        var left = Number((screen.width/2)-(w/2));
        var tops = Number((screen.height/2)-(h/2));"templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

Well, in my case the problem had a different cause, the Windows path Length Check this.

I was installing a library on a virtualenv which made the path get longer. As the library was installed, it created some files under site-packages. This made the path exceed Windows limit throwing this error.

Hope it helps someone =)

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.

In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also:

Get full path of the files in PowerShell

You can also use Select-Object like so:

Get-ChildItem "C:\WINDOWS\System32" *.txt -Recurse | Select-Object FullName

How can I return the sum and average of an int array?

i refer so many results and modified my code its working

foreach (var rate in rateing)
                    sum += Convert.ToInt32(rate.Rate);
                if(rateing.Count()!= 0)
                    float avg = (float)sum / (float)rateing.Count();
                    saloonusers.Rate = avg;
                    saloonusers.Rate = (float)0.0;

String "true" and "false" to boolean

Perhaps str.to_s.downcase == 'true' for completeness. Then nothing can crash even if str is nil or 0.

What are naming conventions for MongoDB?

  1. Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.

  2. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...

  3. MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.

  4. MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id (but this may be be to indicate that _id is intended to be private, internal, never displayed or edited.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/js       <-- Bootstrap JavaScript here

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:


The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:


The CSS file would technically be looking for a folder at:


but your folder is actually in:


So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Creating a .dll file in C#.Net

You need to change project settings. Right click your project, go to properites. In Application tab change output type to class library instead of Windows application.

Lazy Method for Reading Big File in Python?

I'm in a somewhat similar situation. It's not clear whether you know chunk size in bytes; I usually don't, but the number of records (lines) that is required is known:

def get_line():
     with open('4gb_file') as file:
         for i in file:
             yield i

lines_required = 100
gen = get_line()
chunk = [i for i, j in zip(gen, range(lines_required))]

Update: Thanks nosklo. Here's what I meant. It almost works, except that it loses a line 'between' chunks.

chunk = [next(gen) for i in range(lines_required)]

Does the trick w/o losing any lines, but it doesn't look very nice.

Getting Excel to refresh data on sheet from within VBA

You might also try




if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

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

Additionally,this error may occurs in you are using any proxy in command line.

if you export any proxy before , unset it .

$ unset all_proxy && unset ALL_PROXY

document.all vs. document.getElementById

document.all works in Chrome now (not sure when since), but I've been missing it the last 20 years.... Simply a shorter method name than the clunky document.getElementById. Not sure if it works in Firefox, those guys never had any desire to be compatible with the existing web, always creating new standards instead of embracing the existing web.

How to use a class object in C++ as a function parameter

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.


class ANewType
    // ... details

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.

This is illustrated best with an example:

<div my-customer name="Customer XYZ"></div>

and the directive definition:

angular.module('myModule', [])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerName: '@name'
    controllerAs: 'vm',
    bindToController: true,
    controller: ['$http', function($http) {
      var vm = this;

      vm.doStuff = function(pane) {
    link: function(scope, element, attrs) {

When the scope property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.

In very simple terms, the meaning of the binding symbols is:

someObject: '=' (two-way data binding)

someString: '@' (passed directly or through interpolation with double curly braces notation {{}})

someExpression: '&' (e.g. hideDialog())

This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.

The symbol > is not part of the syntax.

However, < does exist as part of the AngularJS component bindings and means one way binding.

Android SDK Manager Not Installing Components

go to sdk folder and right click on SDK manager and run with administrator and enjoy installing.

Retrieving Android API version programmatically

Very easy:

   String manufacturer = Build.MANUFACTURER;
   String model = Build.MODEL;
   int version = Build.VERSION.SDK_INT;
   String versionRelease = Build.VERSION.RELEASE;

Log.e("MyActivity", "manufacturer " + manufacturer
            + " \n model " + model
            + " \n version " + version
            + " \n versionRelease " + versionRelease


E/MyActivity:   manufacturer ManufacturerX
                model SM-T310 
                version 19 
                versionRelease 4.4.2

Multiple line code example in Javadoc comment

I was able to generate good looking HTML files with the following snip-it shown in Code 1.

 * <pre>
 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }

(Code 1)

Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.

   \   \
    G   E-->F

(Fig. 1)

However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.

 * <
 * pre>
 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }
 * </pre>

(Code 2)

where the first <pre> is now broken onto two lines. Code 2 produces generated javadoc HTML file as shown in Fig 2.

< pre> A-->B \ C-->D \ \ G E-->F

(Fig 2)

Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.

* A-->B
*  \
*   C-->D
*    \   \
*     G   E-->F
* </pre></blockquote>

(Code 3)

Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.

Django: multiple models in one template using forms

The MultiModelForm from django-betterforms is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForms in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.

from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile

User = get_user_model()

class UserEditForm(forms.ModelForm):
    class Meta:
        fields = ('email',)

class UserProfileForm(forms.ModelForm):
    class Meta:
        fields = ('favorite_color',)

class UserEditMultiForm(MultiModelForm):
    form_classes = {
        'user': UserEditForm,
        'profile': UserProfileForm,

from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm

User = get_user_model()

class UserSignupView(UpdateView):
    model = User
    form_class = UserEditMultiForm
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super(UserSignupView, self).get_form_kwargs()
            'user': self.object,
            'profile': self.object.profile,
        return kwargs

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:


No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...

How to split a large text file into smaller files with equal number of lines?

you can also use awk

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

How do you save/store objects in SharedPreferences on Android?

Step 1: Copy paste these two functions in your java file.

 public void setDefaults(String key, String value, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);

    public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);

Step 2: to save use:


to retrieve use:

String retrieve= getDefaults("key",this);

You can set different shared preferences by using different key names like:




Disabling user input for UITextfield in swift

you can use UILabel instead if you don't want the user to be able to modify anything in your UITextField

A programmatic solution would be to use enabled property:

yourTextField.enabled = false

A way to do it in a storyboard:

Uncheck the Enabled checkbox in the properties of your UITextField

enter image description here

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

PHP PDO: charset, set names?

$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);

How to create a unique index on a NULL column?

Using SQL Server 2008, you can create a filtered index: (I see Simon added this as a comment, but thought it deserved its own answer as the comment is easily missed.)

Another option is a trigger to check uniqueness, but this could affect performance.

How do I get user IP address in django?

Alexander's answer is great, but lacks the handling of proxies that sometimes return multiple IP's in the HTTP_X_FORWARDED_FOR header.

The real IP is usually at the end of the list, as explained here:

The solution is a simple modification of Alexander's code:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
        ip = request.META.get('REMOTE_ADDR')
    return ip

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(;return false">
    <input type="hidden" name="something" value="1">


function sendForm(form_id){
    var form = $('#'+form_id);
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {

How to upgrade Angular CLI project?


Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide.

See GitHub repository Angular CLI diff for comparing Angular CLI changes.

UPDATED 26/12/2018:

Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.

UPDATED 08/05/2018:

Angular CLI 1.7 introduced ng update.

ng update

A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.

Configuration information for ng update can be found here

1.7 to 6 update

CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.

npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1

UPDATED 30/04/2017:

1.0 Update

You should now follow the Angular CLI migration guide

UPDATED 04/03/2017:

RC Update

You should follow the Angular CLI RC migration guide

UPDATED 20/02/2017:

Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update

The pull request here states the following:

BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.

The angular-cli states the following:

BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.

UPDATED 17/02/2017:

Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -

Global package:

npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init


You should follow the steps from the on GitHub for updating angular via the angular-cli.

Here they are:

Updating angular-cli

To update angular-cli to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

Local project package:

rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init

Running ng init will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.

Check if EditText is empty.

You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    return isEmptyResult;

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        String act = driver.getCurrentUrl();
    }catch(Exception e){

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

    public async Task<string> methodName()
             return Data;


Hope this helps :)

Define a fixed-size list in Java

The public java.util.List subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List specification.
You could find it only in Queue subclasses (for example ArrayBlockingQueue, a bounded blocking queue backed by an array for example) that handle very specific requirements.

In Java, with a List type, you could implement it according to two scenarios :

1) The fixed list size is always both the actual and the maximum size.

It sounds as an array definition. So Arrays.asList() that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.

For example :

Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception

It works also with a collection as input while first we convert it into an array :

Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList([]::new)); // Java 8 way

2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.

You could use inheritance (extends ArrayList) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.

With Guava Forwarding classes you could do :


public class FixedSizeList<T> extends ForwardingList<T> {

  private final List<T> delegate;
  private final int maxSize;

  public FixedSizeList(List<T> delegate, int maxSize) {
    this.delegate = delegate;
    this.maxSize = maxSize;

  @Override protected List<T> delegate() {
    return delegate;

  @Override public boolean add(T element) {
    return super.add(element);

  @Override public void add(int index, T element) {
    super.add(index, element);

  @Override public boolean addAll(Collection<? extends T> collection) {
    return super.addAll(collection);

  @Override public boolean addAll(int index, Collection<? extends T> elements) {
    return super.addAll(index, elements);

  private void assertMaxSizeNotReached(int size) {
    if (delegate.size() + size >= maxSize) {
      throw new RuntimeException("size max reached");


And use it :

List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3); 
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4");  // throws an Exception

Note that with composition, you could use it with any List implementation :

List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3); 

Which is not possible with inheritance.

How do I check if a string contains a specific word?

Another solution for a specific string:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;

You can also use strpos() function.

Unlink of file Failed. Should I try again?

For my Spring Boot project I ran into this errror when attempting to run git stash.

The solution was to killed all of the Java processes running on my machine.

Guzzle 6: no more json() method for responses

Adding ->getContents() doesn't return jSON response, instead it returns as text.

You can simply use json_decode

'module' object has no attribute 'DataFrame'

I have faced similar problem, 'int' object has no attribute 'DataFrame',

This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.

I realized this, and changed my variable to something else, and fixed the error.

How to Get enum item name from its value

I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

Replacing &nbsp; from javascript dom text node

Removes everything between & and ; which all such symbols have. if you juts want to get rid of them.


Scatter plot with error bars

First of all: it is very unfortunate and surprising that R cannot draw error bars "out of the box".

Here is my favourite workaround, the advantage is that you do not need any extra packages. The trick is to draw arrows (!) but with little horizontal bars instead of arrowheads (!!!). This not-so-straightforward idea comes from the R Wiki Tips and is reproduced here as a worked-out example.

Let's assume you have a vector of "average values" avg and another vector of "standard deviations" sdev, they are of the same length n. Let's make the abscissa just the number of these "measurements", so x <- 1:n. Using these, here come the plotting commands:

plot(x, avg,
    ylim=range(c(avg-sdev, avg+sdev)),
    pch=19, xlab="Measurements", ylab="Mean +/- SD",
    main="Scatter plot with error bars"
# hack: we draw arrows but with very special "arrowheads"
arrows(x, avg-sdev, x, avg+sdev, length=0.05, angle=90, code=3)

The result looks like this:

example scatter plot with error bars

In the arrows(...) function length=0.05 is the size of the "arrowhead" in inches, angle=90 specifies that the "arrowhead" is perpendicular to the shaft of the arrow, and the particularly intuitive code=3 parameter specifies that we want to draw an arrowhead on both ends of the arrow.

For horizontal error bars the following changes are necessary, assuming that the sdev vector now contains the errors in the x values and the y values are the ordinates:

plot(x, y,
    xlim=range(c(x-sdev, x+sdev)),
# horizontal error bars
arrows(x-sdev, y, x+sdev, y, length=0.05, angle=90, code=3)

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

I had a similar issue when trying to migrate a Drupal website from one local host to another. From Mac running XAMMP to Windows running WAMP.

This was the error message I kept getting when trying to access the pages of the website.

PDOException: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. 
in drupal_get_installed_schema_version() (line 155 of C:\wamp\www\chia\includes\

In settings.php, I've changed everything correctly, database name, user and password.

$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'mydatabasename',
      'username' => 'mydbusername',
      'password' => 'mydbpass',
      'host' => 'localhost',
      'port' => '8889',
      'driver' => 'mysql',
      'prefix' => '',

After a couple of hours of mindless google searching I've changed the port to a empty value:

'port' => '',

And after that the site loaded properly.

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

HTML how to clear input using javascript?

You could use a placeholder because it does it for you, but for old browsers that don't support placeholder, try this:

function clearThis(target) {
    if (target.value == "[email protected]") {
        target.value = "";
function replace(target) {
    if (target.value == "" || target.value == null) {
        target.value == "[email protected]";
<input type="text" name="email" value="[email protected]" size="x" onfocus="clearThis(this)" onblur="replace(this)" />

CODE EXPLAINED: When the text box has focus, clear the value. When text box is not focused AND when the box is blank, replace the value.

I hope that works, I have been having the same issue, but then I tried this and it worked for me.

Comparing two NumPy arrays for equality, element-wise

Now use np.array_equal. From documentation:

np.array_equal([1, 2], [1, 2])
np.array_equal(np.array([1, 2]), np.array([1, 2]))
np.array_equal([1, 2], [1, 2, 3])
np.array_equal([1, 2], [1, 4])

How do you Programmatically Download a Webpage in Java

Well, you could go with the built-in libraries such as URL and URLConnection, but they don't give very much control.

Personally I'd go with the Apache HTTPClient library.
Edit: HTTPClient has been set to end of life by Apache. The replacement is: HTTP Components

Fill remaining vertical space - only CSS

you need javascript and some client side calculations:

you will need jquery to effectively achieve what you want. this function is very simple but very effective:

(function () {

    var heights = $("#wrapper").outerHeight(true);
    var outerHeights = $("#first").outerHeight(true);
    jQuery('#second').css('height', (heights - outerHeights) + "px");


first it detects the wrapper height, as it is set to 100% it's different everytime (it depends on what screen you are landing). in the second step it gives the #second div the appropriate height subtracting from the wrapper height the #first div height. the result is the available height left in the wrapper div

How to use a BackgroundWorker?

You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

public Form1()

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;

private void button1_Click(object sender, EventArgs e)

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    for (int i = 0; i < 100; i++)

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    progressBar1.Value = e.ProgressPercentage;

NodeJS - What does "socket hang up" actually mean?

There are two cases when socket hang up gets thrown:

When you are a client

When you, as a client, send a request to a remote server, and receive no timely response. Your socket is ended which throws this error. You should catch this error and decide how to handle it: whether retry the request, queue it for later, etc.

When you are a server/proxy

When you, as a server, perhaps a proxy server, receive a request from a client, then start acting upon it (or relay the request to the upstream server), and before you have prepared the response, the client decides to cancel/abort the request.

This stack trace shows what happens when a client cancels the request.

Trace: { [Error: socket hang up] code: 'ECONNRESET' }
    at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
    at ClientRequest.emit (events.js:117:20)
    at Socket.socketCloseListener (http.js:1526:9)
    at Socket.emit (events.js:95:17)
    at TCP.close (net.js:465:12)

Line http.js:1526:9points to the same socketCloseListener mentioned by @Blender, particularly:

// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());


function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;

This is a typical case if the client is a user in the browser. The request to load some resource/page takes long, and users simply refresh the page. Such action causes the previous request to get aborted which on your server side throws this error.

Since this error is caused by the wish of a client, they don't expect to receive any error message. So, no need to consider this error as critical. Just ignore it. This is encouraged by the fact that on such error the res socket that your client listened to is, though still writable, destroyed.

console.log(res.socket.destroyed); //true

So, no point to send anything, except explicitly closing the response object:


However, what you should do for sure if you are a proxy server which has already relayed the request to the upstream, is to abort your internal request to the upstream, indicating your lack of interest in the response, which in turn will tell the upstream server to, perhaps, stop an expensive operation.

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;

 * SpringMVC????
 * @author ??([email protected])
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;

    private WebContextHolder() {

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();

    public HttpSession getSession() {
        return getSession(true);

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);

    public String getSessionId() {
        return getSession().getId();

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            return null;


How to properly URL encode a string in PHP?

The cunningly-named urlencode() and urldecode().

However, you shouldn't need to use urldecode() on variables that appear in $_POST and $_GET.

Write HTML string in JSON

4 Things You Must Do When Putting HTML in JSON:

1) Escape quotation marks used around HTML attributes like so <img src=\"someimage.png\" />

2) Escape the forward slash in HTML end tags. <div>Hello World!<\/div>. This is an ancient artifact of an old HTML spec that didn't want HTML parsers to get confused when putting strings in a <SCRIPT> tag. For some reason, today’s browsers still like it.

3) This one was totally bizarre. You should include a space between the tag name and the slash on self-closing tags. I have no idea why this is, but on MOST modern browsers, if you try using javascript to append a <li> tag as a child of an unordered list that is formatted like so: <ul/>, it won't work. It gets added to the DOM after the ul tag. But, if the code looks like this: <ul /> (notice the space before the /), everything works fine. Very strange indeed.

4) Be sure to encode any quotation marks that might be included in (bad) HTML content. This is the only thing that would really break the JSON by accidentally terminating the string early. Any " characters should be encoded as &quot; if it is meant to be included as HTML content.


How to combine GROUP BY and ROW_NUMBER?

Undoubtly this can be simplified but the results match your expectations.

The gist of this is to

  • Calculate the maximum price in a seperate CTE for each t2ID
  • Calculate the total price in a seperate CTE for each t2ID
  • Combine the results of both CTE's

SQL Statement

;WITH MaxPrice AS ( 
    SELECT  t2ID
            , t1ID
    FROM    (       
                SELECT  t2.ID AS t2ID
                        , t1.ID AS t1ID
                        , rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
                FROM    @t1 t1
                        INNER JOIN @relation r ON r.t1ID = t1.ID        
                        INNER JOIN @t2 t2 ON t2.ID = r.t2ID
            ) maxt1
    WHERE   maxt1.rn = 1                            
, SumPrice AS (
    SELECT  t2ID = t2.ID
            , Price = SUM(Price)
    FROM    @t1 t1
            INNER JOIN @relation r ON r.t1ID = t1.ID
            INNER JOIN @t2 t2 ON t2.ID = r.t2ID
        , t2.Name
        , t2.Orders
        , mp.t1ID
        , t1.ID
        , t1.Name
        , sp.Price
FROM    @t2 t2
        INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
        INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
        INNER JOIN @t1 t1 ON t1.ID = mp.t1ID

How to get the current time in Python

The time module can import all sorts of time stuff, inculduing sleep and other types of stuff including - the current time type

import time
time.strftime("%T", time.localtime())

The output should look like this


MySQL - How to select data by string length

select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**

How to set default Checked in checkbox ReactJS?

There are a few ways to accomplish this, here's a few:

Written using State Hooks:

function Checkbox() {
  const [checked, setChecked] = React.useState(true);

  return (
      <input type="checkbox"
        onChange={() => setChecked(!checked)}
      Check Me!

  <Checkbox />,

Here is a live demo on JSBin.

Written using Components:

class Checkbox extends React.Component {
  constructor(props) {
    this.state = {
      isChecked: true,
  toggleChange = () => {
      isChecked: !this.state.isChecked,
  render() {
    return (
        <input type="checkbox"
        Check Me!

  <Checkbox />,

Here is a live demo on JSBin.

Is there a wikipedia API just for retrieve content summary?

I tried @Michael Rapadas and @Krinkle's solution but in my case I had trouble to find some articles depending of the capitalization. Like here:

Note I truncated the response with exsentences=1

Apparently "title normalization" was not working correctly:

Title normalization converts page titles to their canonical form. This means capitalizing the first character, replacing underscores with spaces, and changing namespace to the localized form defined for that wiki. Title normalization is done automatically, regardless of which query modules are used. However, any trailing line breaks in page titles (\n) will cause odd behavior and they should be stripped out first.

I know I could have sorted out the capitalization issue easily but there was also the inconvenience of having to cast the object to an array.

So because I just really wanted the very first paragraph of a well-known and defined search (no risk to fetch info from another articles) I did it like this:

Note in this case I did the truncation with limit=1

This way:

  1. I can access the response data very easily.
  2. The response is quite small.

But we have to keep being careful with the capitalization of our search.

More info:

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

callback to handle completion of pipe

Code snippet for piping content from web via http(s) to filesystem. As @starbeamrainbowlabs noticed event finish does job

var tmpFile = "/tmp/somefilename.doc";

var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
  // pipe done here, do something with file

var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
  return response.pipe(ws);

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

Notice: Undefined offset: 0 in

function getEffectiveVotes($id) 

According to the function header, there is only one parameter variable ($id). Thus, on line 27, the votes[] array is undefined and out of scope. You need to add another parameter value to the function header so that function getEffectiveVotes() knows to expect two parameters. I'm rusty, but something like this would work.

function getEffectiveVotes($id, $votes)

I'm not saying this is how it should be done, but you might want to research how PHP passes its arrays and decide if you need to explicitly state to pass it by reference

function getEffectiveVotes($id &$votes)    <---I forget, no time to look it up right now.

Lastly, call function getEffectiveVotes() with both arguments wherever it is supposed to be called.


How to set a timer in android

I used to use (Timer, TimerTask) as well as Handler to kick off (time-consuming) tasks periodically. Now I've switched the whole to RxJava. RxJava provides Observable.timer which is simpler, less error-prone, hassle-free to use.

public class BetterTimerFragment extends Fragment {
  public static final String TAG = "BetterTimer";
  private TextView timeView;
  private Subscription timerSubscription;

  public View onCreateView(LayoutInflater inflater,
                           @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_timer, container, false);

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    timeView = (TextView) view.findViewById(;

  public void onResume() {

    // Right after the app is visible to users, delay 2 seconds
    // then kick off a (heavy) task every 10 seconds.
    timerSubscription = Observable.timer(2, 10, TimeUnit.SECONDS)
        .map(new Func1<Long, String>() {
          public String call(Long unused) {
            // TODO: Probably do time-consuming work here.
            // This runs on a different thread than the main thread.
            return "Time: " + System.currentTimeMillis();
        .subscribe(new Action1<String>() {
          public void call(String timeText) {
            // The result will then be propagated back to the main thread.
        }, new Action1<Throwable>() {
          public void call(Throwable throwable) {
            Log.e(TAG, throwable.getMessage(), throwable);

  public void onPause() {

    // Don't kick off tasks when the app gets invisible.

How to join two sets in one line without using "|"

If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update():


The return value is None, but S will be updated to be the union of the original S and T.

javascript create empty array of a given size

You can use both javascript methods repeat() and split() together.

" ".repeat(10).split(" ")

This code will create an array that has 10 item and each item is empty string.

const items = " ".repeat(10).split(" ")

document.getElementById("context").innerHTML =, index) => index)

console.log("items: ", items)
<pre id="context">


jQuery val is undefined?

try: $('#editorTitle').attr('value') ?

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

How can I confirm a database is Oracle & what version it is using SQL?

SQL> SELECT version FROM v$instance;

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()

Test code:

foreach(var item in newList)
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
        Console.WriteLine("\t Name: {0}", child.Name);


School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

How to trim a file extension from a String in JavaScript?

Node.js remove extension from full path keeping directory for example did path/hello.html -> hello, but if you want path/hello.html -> path/hello, you can use this:

#!/usr/bin/env node
const path = require('path');
const filename = 'path/hello.html';
const filename_parsed = path.parse(filename);

outputs directory as well:

path/hello also achieves this, but I find this approach a bit more semantically pleasing.

Tested in Node.js v10.15.2.

The ResourceConfig instance does not contain any root resource classes

that issue is because jersey can't find a dependecy package for your rest service declarated

check your project package distribution and assert that is equals to your web.xml param value

Difference between decimal, float and double in .NET?

This has been an interesting thread for me, as today, we've just had a nasty little bug, concerning decimal having less precision than a float.

In our C# code, we are reading numeric values from an Excel spreadsheet, converting them into a decimal, then sending this decimal back to a Service to save into a SQL Server database.

Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
    decimal value = 0;
    Decimal.TryParse(cellValue.ToString(), out value);

Now, for almost all of our Excel values, this worked beautifully. But for some, very small Excel values, using decimal.TryParse lost the value completely. One such example is

  • cellValue = 0.00006317592

  • Decimal.TryParse(cellValue.ToString(), out value); // would return 0

The solution, bizarrely, was to convert the Excel values into a double first, and then into a decimal:

Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
    double valueDouble = 0;
    double.TryParse(cellValue.ToString(), out valueDouble);
    decimal value = (decimal) valueDouble;

Even though double has less precision than a decimal, this actually ensured small numbers would still be recognised. For some reason, double.TryParse was actually able to retrieve such small numbers, whereas decimal.TryParse would set them to zero.

Odd. Very odd.

How to convert empty spaces into null values, using SQL Server?

This code generates some SQL which can achieve this on every table and column in the database:

   WHERE [' + COLUMN_NAME + '] = '''''
    DATA_TYPE IN ('char','nchar','varchar','nvarchar')

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily) = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    //if it was prevented, make sure we don't get a build up of buttons

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.


Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

select count(distinct(concat(tag,entryId)))
from customers
where id>0

In the output it will display the count of unique values Hope this helps

Unexpected end of file error

I encountered that error when I forgot to uncheck the Precompiled header from the additional options in the wizard after naming a new Win32 console application.

Because I don't need stdafx.h library, I removed it by going to Project menu, then click Properties or [name of our project] Properties or simply press Alt + F7. On the dropdownlist beside configuration, select All Configurations. Below that, is a tree node, click Configuration Properties, then C/C++. On the right pane, select Create/Use Precompiled Header, and choose Not using Precompiled Header.

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"