Programs & Examples On #A0poster

a0poster is a class for the creation of a scientific poster in LaTex.

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

Sorting arraylist in alphabetical order (case insensitive)

Starting from Java 8 you can use Stream:

List<String> sorted = Arrays.asList(
                          names.stream().sorted(
                              (s1, s2) -> s1.compareToIgnoreCase(s2)
                          ).toArray(String[]::new)
                      );

It gets a stream from that ArrayList, then it sorts it (ignoring the case). After that, the stream is converted to an array which is converted to an ArrayList.

If you print the result using:

System.out.println(sorted);

you get the following output:

[ananya, Athira, bala, jeena, Karthika, Neethu, Nithin, seetha, sudhin, Swetha, Tony, Vinod]

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):

def execute_run(rp): 
   ... do something 

pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
    for en in TESTED_ENERGIES:
        for ecut in TESTED_E_CUT:
            rp = RunParams(
                simulations, DEST_DIR,
                PARTICLE, mat, 960, 0.125, ecut, en
            )
            pool.submit(execute_run, rp)
pool.join()

Basically:

  • pool = ThreadPoolExecutor(6) creates a pool for 6 threads
  • Then you have bunch of for's that add tasks to the pool
  • pool.submit(execute_run, rp) adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function.
  • pool.join waits until all tasks are done.

Why declare unicode by string in python?

Those are two different things, as others have mentioned.

When you specify # -*- coding: utf-8 -*-, you're telling Python the source file you've saved is utf-8. The default for Python 2 is ASCII (for Python 3 it's utf-8). This just affects how the interpreter reads the characters in the file.

In general, it's probably not the best idea to embed high unicode characters into your file no matter what the encoding is; you can use string unicode escapes, which work in either encoding.


When you declare a string with a u in front, like u'This is a string', it tells the Python compiler that the string is Unicode, not bytes. This is handled mostly transparently by the interpreter; the most obvious difference is that you can now embed unicode characters in the string (that is, u'\u2665' is now legal). You can use from __future__ import unicode_literals to make it the default.

This only applies to Python 2; in Python 3 the default is Unicode, and you need to specify a b in front (like b'These are bytes', to declare a sequence of bytes).

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

Creating files in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

Retrofit 2.0 how to get deserialised error response.body

try{
                ResponseBody response = ((HttpException) t).response().errorBody();
                JSONObject json = new JSONObject( new String(response.bytes()) );
                errMsg = json.getString("message");
            }catch(JSONException e){
                return t.getMessage();
            }
            catch(IOException e){
                return t.getMessage();
            }

What is the difference between <html lang="en"> and <html lang="en-US">?

RFC 3066 gives the details of the allowed values (emphasis and links added):

All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.

I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:

Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.

By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.

A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse):

Type: variant

Subtag: scouse

Description: Scouse

Added: 2006-09-18

Prefix: en

Comments: English Liverpudlian dialect known as 'Scouse'

There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad (17th century French).


The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:

Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.

I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.

Python: No acceptable C compiler found in $PATH when installing python

for Ubuntu / Debian :

# sudo apt-get install build-essential

For RHEL/CentOS

#rpm -qa | grep gcc
# yum install gcc glibc glibc-common gd gd-devel -y

or

 # yum groupinstall "Development tools" -y

More details refer the link

Installation failed with message Invalid File

In my case , there was a single qutation ' in project directory and after removing it resolved

LINQ - Left Join, Group By, and Count

Consider using a subquery:

from p in context.ParentTable 
let cCount =
(
  from c in context.ChildTable
  where p.ParentId == c.ChildParentId
  select c
).Count()
select new { ParentId = p.Key, Count = cCount } ;

If the query types are connected by an association, this simplifies to:

from p in context.ParentTable 
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

Twitter bootstrap remote modal shows same content every time

For bootstrap 3 you should use:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

Using Spring RestTemplate in generic method with generic parameter

I am using org.springframework.core.ResolvableType for a ListResultEntity :

    ResolvableType resolvableType = ResolvableType.forClassWithGenerics(ListResultEntity.class, itemClass);
    ParameterizedTypeReference<ListResultEntity<T>> typeRef = ParameterizedTypeReference.forType(resolvableType.getType());

So in your case:

public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        ParameterizedTypeReference.forType(ResolvableType.forClassWithGenerics(ResponseWrapper.class, clazz)));
    return response;
}

This only makes use of spring and of course requires some knowledge about the returned types (but should even work for things like Wrapper>> as long as you provide the classes as varargs )

How to search for a part of a word with ElasticSearch

I am using this and got I worked

"query": {
        "query_string" : {
            "query" : "*test*",
            "fields" : ["field1","field2"],
            "analyze_wildcard" : true,
            "allow_leading_wildcard": true
        }
    }

How can I add a PHP page to WordPress?

Try this:

/**
 * The template for displaying demo page
 *
 * template name: demo template
 *
 */

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

What does ^M character mean in Vim?

In FreeBSD, you can clear the ^M manually by typing the following:

:%s/ Ctrl+V, then Ctrl+M, then Ctrl+M again.

Can I remove the URL from my print css, so the web address doesn't print?

This solution will do the trick in Chrome and Opera by setting margin to 0 in a css @page directive. It will not (currently) work for other browsers though...

node.js remove file

You may use fs.unlink(path, callback) function. Here is an example of the function wrapper with "error-back" pattern:

_x000D_
_x000D_
// Dependencies._x000D_
const fs = require('fs');_x000D_
_x000D_
// Delete a file._x000D_
const deleteFile = (filePath, callback) => {_x000D_
  // Unlink the file._x000D_
  fs.unlink(filePath, (error) => {_x000D_
    if (!error) {_x000D_
      callback(false);_x000D_
    } else {_x000D_
      callback('Error deleting the file');_x000D_
    }_x000D_
  })_x000D_
};
_x000D_
_x000D_
_x000D_

How to set OnClickListener on a RadioButton in Android?

For Kotlin Here is added the lambda expression and Optimized the Code.

   radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
        run {
            when (optionId) {
                R.id.radioButton1 -> {
                    // do something when radio button 1 is selected
                }
                R.id.radioButton2 -> {
                    // do something when radio button 2 is selected
                }
                // add more cases here to handle other buttons in the your RadioGroup
            }
        }
    }

Hope this will help you. Thanks!

How do I convert this list of dictionaries to a csv file?

import csv

with open('file_name.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(('colum1', 'colum2', 'colum3'))
    for key, value in dictionary.items():
        writer.writerow([key, value[0], value[1]])

This would be the simplest way to write data to .csv file

Compute elapsed time

Something like a "Stopwatch" object comes to my mind:

Usage:

var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
            st.stop(); // Stop it 5 seconds later...
            alert(st.getSeconds());
            }, 5000);

Implementation:

function Stopwatch(){
  var startTime, endTime, instance = this;

  this.start = function (){
    startTime = new Date();
  };

  this.stop = function (){
    endTime = new Date();
  }

  this.clear = function (){
    startTime = null;
    endTime = null;
  }

  this.getSeconds = function(){
    if (!endTime){
    return 0;
    }
    return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
  }

  this.getMinutes = function(){
    return instance.getSeconds() / 60;
  }      
  this.getHours = function(){
    return instance.getSeconds() / 60 / 60;
  }    
  this.getDays = function(){
    return instance.getHours() / 24;
  }   
}

PHP Include for HTML?

Try to get some debugging information, could be that the file path is wrong, for example.

Try these two things:- Add this line to the top of your sample page:

<?php error_reporting(E_ALL);?>

This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page

Additionally you can change include() to require()

<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>

This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..

You can post the error descriptions here, if you get any, and you are unable to figure out what it means..

Javascript regular expression password validation having special characters

it,s work perfect for me and i am sure will work for you guys checkout it easy and accurate

var regix = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=. 
            {8,})");

if(regix.test(password) == false ) {
     $('.messageBox').html(`<div class="messageStackError">
       password must be a minimum of 8 characters including number, Upper, Lower And 
       one special character
     </div>`);
}
else
{
        $('form').submit();
}

send mail from linux terminal in one line

You can also use sendmail:

/usr/sbin/sendmail [email protected] < /file/to/send

Get SELECT's value and text in jQuery

on the basis of your only jQuery tag :)

HTML

<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>

For text --

$(document).ready(function() {
    $("#my-select").change(function() {
        alert($('#my-select option:selected').html());
    });
});

For value --

$(document).ready(function() {
    $("#my-select").change(function() {
        alert($(this).val());
    });
});

The data-toggle attributes in Twitter Bootstrap

For example, say you were creating a web application to list and display recipes. You might want your customers to be able to sort the list, display features of the recipes, and so on before they choose the recipe to open. In order to do this, you need to associate things like cooking time, primary ingredient, meal position, and so on right inside the list elements for the recipes.

<li><a href="recipe1.html">Borscht</a></li>
<li><a href="recipe2.html">Chocolate Mousse</a></li>
<li><a href="recipe3.html">Almond Radiccio Salad</a></li>
<li><a href="recipe4.html">Deviled Eggs</a></li>

In order to get that information into the page, you could do many different things. You could add comments to each LI element, you could add rel attributes to the list items, you could place all the recipes in separate folders based on time, meal, and ingredient (i.e. ). The solution that most developers took was to use class attributes to store information about the current element. This has several advantages:

  • You can store multiple classes on an element
  • The class names can be human readable
  • It’s easy to access classes with JavaScript (className)
  • The class is associated with the element it’s on

But there are some major drawbacks to this method:

  • You have to remember what the classes do. If you forget or a new developer takes over the project, the classes might be removed or changed without realizing that that affects how the application runs.
  • Classes are also used for styling with CSS, and you might duplicate CSS classes with data classes by mistake, ending up with strange styles on your live pages.
  • It’s more difficult to add on multiple data elements. If you have multiple data elements, you need to access them in some way with your JavaScript, either by the name of the class or the position in the class list. But it’s easy to mess up.

All the other methods I suggested had these problems as well as others. But since it was the only way to quickly and easily include data, that’s what we did. HTML5 Data Attributes to the Rescue

HTML5 added a new type of attribute to any element—the custom data element (data-*). These are custom (denoted by the *) attributes that you can add to your HTML elements to define any type of data you want. They consist of two parts:

Attribute Name This is the name of the attribute. It must be at least one lowercase character and have the prefix data-. For example: data-main-ingredient, data-cooking-time, data-meal. This is the name of your data.

Attribute Vaule Like any other HTML attribute, you include the data itself in quotes separated by an equal sign. This data can be any string that is valid on a web page. For example: data-main-ingredient="chocolate".

You can then apply these data attributes to any HTML element you want. For example, you could define the information in the example list above:

<li data-main-ingredient="beets" data-cooking-time="1 hour" data-meal="dinner"><a href="recipe1.html">Borscht</a></li>
<li data-main-ingredient="chocolate" data-cooking-time="30 minutes" data-meal="dessert"><a href="recipe2.html">Chocolate Mousse</a></li>
<li data-main-ingredient="radiccio" data-cooking-time="20 minutes" data-meal="dinner"><a href="recipe1.html">Almond Radiccio Salad</a></li>
<li data-main-ingredient="eggs" data-cooking-time="15 minutes" data-meal="appetizer"><a href="recipe1.html">Deviled Eggs</a></li>

Once you have that information in your HTML, you will be able to access it with JavaScript and manipulate the page based on that data.

Getting rid of all the rounded corners in Twitter Bootstrap

With SASS Bootstrap - if you are compiling Bootstrap yourself - you can set all border radius (or more specific) simply to zero:

$border-radius:               0;
$border-radius-lg:            0;
$border-radius-sm:            0;

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

How to perform a sum of an int[] array

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:

int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
    sum += numbers[i];
}
System.out.println("The sum is: " + sum);

Rails 4: how to use $(document).ready() with turbo-links

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

How to hide axes and gridlines in Matplotlib (python)

Turn the axes off with:

plt.axis('off')

And gridlines with:

plt.grid(b=None)

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

Use a content script to access the page context variables and functions

You can use a utility function I've created for the purpose of running code in the page context and getting back the returned value.

This is done by serializing a function to a string and injecting it to the web page.

The utility is available here on GitHub.

Usage examples -



// Some code that exists only in the page context -
window.someProperty = 'property';
function someFunction(name = 'test') {
    return new Promise(res => setTimeout(()=>res('resolved ' + name), 1200));
}
/////////////////

// Content script examples -

await runInPageContext(() => someProperty); // returns 'property'

await runInPageContext(() => someFunction()); // returns 'resolved test'

await runInPageContext(async (name) => someFunction(name), 'with name' ); // 'resolved with name'

await runInPageContext(async (...args) => someFunction(...args), 'with spread operator and rest parameters' ); // returns 'resolved with spread operator and rest parameters'

await runInPageContext({
    func: (name) => someFunction(name),
    args: ['with params object'],
    doc: document,
    timeout: 10000
} ); // returns 'resolved with params object'


How do I create a link using javascript?

_x000D_
_x000D_
    <script>_x000D_
      _$ = document.querySelector  .bind(document) ;_x000D_
_x000D_
        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
        var a   =  document.createElement( 'a' )_x000D_
        a.text  = "Download example" _x000D_
        a.href  = "//bit\.do/DeezerDL"_x000D_
_x000D_
        AppendLinkHere.appendChild( a )_x000D_
        _x000D_
_x000D_
     // a.title = 'Well well ... _x000D_
        a.setAttribute( 'title', _x000D_
                         'Well well that\'s a link'_x000D_
                      );_x000D_
    </script>
_x000D_
_x000D_
_x000D_

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

Remove whitespaces inside a string in javascript

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.

update

This answer only applies to older browsers. Newer browsers apparently support trim() natively.

In Java, how do I check if a string contains a substring (ignoring case)?

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);

How to run a C# application at Windows startup?

Try this code:

private void RegisterInStartup(bool isChecked)
{
    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (isChecked)
    {
        registryKey.SetValue("ApplicationName", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("ApplicationName");
    }
}

Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

CSS Circle with border

Here is a jsfiddle so you can see an example of this working.

HTML code:

<div class="circle"></div>

CSS code:

_x000D_
_x000D_
.circle {_x000D_
        /*This creates a 1px solid red border around your element(div) */_x000D_
        border:1px solid red;_x000D_
        background-color: #FFFFFF;_x000D_
        height: 100px;_x000D_
        /* border-radius 50% will make it fully rounded. */_x000D_
        border-radius: 50%;_x000D_
        -moz-border-radius:50%;_x000D_
        -webkit-border-radius: 50%;_x000D_
        width: 100px;_x000D_
    }
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_

How to convert a huge list-of-vector to a matrix more efficiently?

You can also use,

output <- as.matrix(as.data.frame(z))

The memory usage is very similar to

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Which can be verified, with mem_changed() from library(pryr).

Modifying a file inside a jar

most of the answers above saying you can't do it for class file.

Even if you want to update class file you can do that also. All you need to do is that drag and drop the class file from your workspace in the jar.

In case you want to verify your changes in class file , you can do it using a decompiler like jd-gui.

java.net.SocketException: Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

Android webview launches browser when calling loadurl

Use this:

lWebView.setWebViewClient(new WebViewClient());

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

What's the HTML to have a horizontal space between two objects?

I guess what you want is:

&nbsp;

But this is usually not a nice way to align some content. You better put your different content in

<div>

tags and then use css for proper alignment.


You can also check out this post with useful extra info:

Save a file in json format using Notepad++

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.

Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.

Thanks, -Sam

Please look at the pic, it will give you a better idea..

How to print the array?

There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.

I would suggest something like this:

int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
   for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
        printf( "%d", my_array[index][jdex] );
        printf( "\n" );
   }
}

The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.

What .NET collection provides the fastest search

You should read this blog that speed tested several different types of collections and methods for each using both single and multi-threaded techniques.

According to the results, a BinarySearch on a List and SortedList were the top performers constantly running neck-in-neck when looking up something as a "value".

When using a collection that allows for "keys", the Dictionary, ConcurrentDictionary, Hashset, and HashTables performed the best overall.

Update just one gem with bundler

bundler update --source gem-name will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).

GIT remote: [email protected]:organization/repo-name.git revision: c810f4a29547b60ca8106b7a6b9a9532c392c954

can be found at github.com/organization/repo-name/commits/c810f4a2 (I used shorthand 8 character commit hash for the url)

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

Graph implementation C++

Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.

#include <iostream>
using namespace std;


// 1 ->2 
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;

// Structure of a vertex
struct vertex {
   int i;
   struct node *list;
   struct vertex *next;
};
typedef struct vertex * VPTR;

// Struct of adjacency list
struct node {
    struct vertex * n;
    struct node *next;
};

typedef struct node * NODEPTR;

class Graph {
    public:
        // list of nodes chained together
        VPTR V;
        Graph() {
            V = NULL;
        }
        void addEdge(int, int);
        VPTR  addVertex(int);
        VPTR existVertex(int i);
        void listVertex();
};

// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
    VPTR temp  = V;
    while(temp != NULL) {
        if(temp->i == i) {
            return temp;
        }
        temp = temp->next;
    }
   return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
    VPTR temp = new(struct vertex);
    temp->list = NULL;
    temp->i = i;
    temp->next = NULL;

    VPTR *curr = &V;
    while(*curr) {
        curr = &(*curr)->next;
    }
    *curr = temp;
    return temp;
}

// Add a node from vertex i to j. 
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {

    VPTR v_i = existVertex(i);   
    VPTR v_j = existVertex(j);   
    if(v_i == NULL) {
        v_i = addVertex(i);
    }
    if(v_j == NULL) {
        v_j = addVertex(j);
    }

    NODEPTR *temp = &(v_i->list);
    while(*temp) {
        temp = &(*temp)->next;
    }
    *temp = new(struct node);
    (*temp)->n = v_j;
    (*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
    VPTR temp = V;
    while(temp) {
        cout <<temp->i <<" ";
        temp = temp->next;
    }
    cout <<"\n";

}

// Client program
int main() {
    Graph G;
    G.addEdge(1, 2);
    G.listVertex();

}

With the above code, you can expand to do DFS/BFS etc.

How can I change the color of a Google Maps marker?

To customize markers, you can do it from this online tool: https://materialdesignicons.com/

In your case, you want the map-marker which is available here: https://materialdesignicons.com/icon/map-marker and which you can customize online.

If you simply want to change the default Red color to Blue, you can load this icon: http://maps.google.com/mapfiles/ms/icons/blue-dot.png

It's been mentioned in this thread: https://stackoverflow.com/a/32651327/6381715

Best practices for Storyboard login screen, handling clearing of data upon logout

Doing this from the app delegate is NOT recommended. AppDelegate manages the app life cycle that relate to launching, suspending, terminating and so on. I suggest doing this from your initial view controller in the viewDidAppear. You can self.presentViewController and self.dismissViewController from the login view controller. Store a bool key in NSUserDefaults to see if it's launching for the first time.

How to use npm with node.exe?

Here is a guide by @CTS_AE on how to use NPM with standalone node.exe: https://stackoverflow.com/a/31148216/228508

  1. Download the node.exe stand-alone from nodejs.org
  2. Grab an NPM release zip off of github https://github.com/npm/npm/releases
  3. Create a folder named: node_modules in the same folder as node.exe
  4. Extract the NPM zip into the node_modules folder
  5. Rename the extracted npm folder to npm and remove any versioning ie: npm-3.3.4 –> npm.
  6. Copy npm.cmd out of the /npm/bin/ folder into the root folder with node.exe

How to use LocalBroadcastManager?

On Receiving end:

  • First register LocalBroadcast Receiver
  • Then handle incoming intent data in onReceive.

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
    
          LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
          lbm.registerReceiver(receiver, new IntentFilter("filter_string"));
      }
    
      public BroadcastReceiver receiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              if (intent != null) {
                  String str = intent.getStringExtra("key");
                  // get all your data from intent and do what you want 
              }
          }
      };
    

On Sending End:

   Intent intent = new Intent("filter_string");
   intent.putExtra("key", "My Data");
   // put your all data using put extra 

   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

How do I create ColorStateList programmatically?

Bouncing off the answer by Jonathan Ellis, in Kotlin you can define a helper function to make the code a bit more idiomatic and easier to read, so you can write this instead:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf can be implemented like this:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

I also have:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

So that I can call the same function name, no matter if it's a selector or single color.

Difference between Method and Function?

Programmers from structural programming language background know it as a function while in OOPS it's called a method.

But there's not any difference between the two.

In the old days, methods did not return values and functions did. Now they both are used interchangeably.

How do I remove a submodule?

You must remove the entry in .gitmodules and .git/config, and remove the directory of the module from the history:

git rm --cached path/to/submodule

If you'll write on git's mailing list probably someone will do a shell script for you.

Make sure that the controller has a parameterless public constructor error

I had the same issue and I resolved it by making changes in the UnityConfig.cs file In order to resolve the dependency issue in the UnityConfig.cs file you have to add:

public static void RegisterComponents()    
{
    var container = new UnityContainer();
    container.RegisterType<ITestService, TestService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

How do I redirect to the previous action in ASP.NET MVC?

A suggestion for how to do this such that:

  1. the return url survives a form's POST request (and any failed validations)
  2. the return url is determined from the initial referral url
  3. without using TempData[] or other server-side state
  4. handles direct navigation to the action (by providing a default redirect)

.

public ActionResult Create(string returnUrl)
{
    // If no return url supplied, use referrer url.
    // Protect against endless loop by checking for empty referrer.
    if (String.IsNullOrEmpty(returnUrl)
        && Request.UrlReferrer != null
        && Request.UrlReferrer.ToString().Length > 0)
    {
        return RedirectToAction("Create",
            new { returnUrl = Request.UrlReferrer.ToString() });
    }

    // Do stuff...
    MyEntity entity = GetNewEntity();

    return View(entity);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
    try
    {
        // TODO: add create logic here

        // If redirect supplied, then do it, otherwise use a default
        if (!String.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index");
    }
    catch
    {
        return View();  // Reshow this view, with errors
    }
}

You could use the redirect within the view like this:

<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
    <a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>

How can I login to a website with Python?

Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.

All you need is to POST to the auth/login URL a form-encoded blob with the various fields you see there (forget the labels for, they're decoration for human visitors). handle=whatever&password-clear=pwd and so on, as long as you know the values for the handle (AKA email) and password you should be fine.

Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie header validating your session (be sure to save that cookie and send it back on further interaction along the session!).

Auto submit form on page load

You can submit any form automatically on page load simply by adding a snippet of javascript code to your body tag referencing the form name like this....

<body onload="document.form1.submit()">

Express.js Response Timeout

There is already a Connect Middleware for Timeout support:

var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4

app.use(timeout(120000));
app.use(haltOnTimedout);

function haltOnTimedout(req, res, next){
  if (!req.timedout) next();
}

If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.

Side Note:

Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

Android Calling JavaScript functions in WebView

Modification of @Ilya_Gazman answer

    private void callJavaScript(WebView view, String methodName, Object...params){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("javascript:try{");
        stringBuilder.append(methodName);
        stringBuilder.append("(");
        String separator = "";
        for (Object param : params) {               
            stringBuilder.append(separator);
            separator = ",";
            if(param instanceof String){
                stringBuilder.append("'");
            }
                stringBuilder.append(param.toString().replace("'", "\\'"));
            if(param instanceof String){
                stringBuilder.append("'");
            }

        }
        stringBuilder.append(")}catch(error){console.error(error.message);}");
        final String call = stringBuilder.toString();
        Log.i(TAG, "callJavaScript: call="+call);


        view.loadUrl(call);
    }

will correctly create JS calls e.g.

callJavaScript(mBrowser, "alert", "abc", "def");
//javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
callJavaScript(mBrowser, "alert", 1, true, "abc");
//javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}

Note that objects will not be passed correctly - but you can serialize them before passing as an argument.

Also I've changed where the error goes, I've diverted it to the console log which can be listened by:

    webView.setWebChromeClient(new CustomWebChromeClient());

and client

class CustomWebChromeClient extends WebChromeClient {
    private static final String TAG = "CustomWebChromeClient";

    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
                cm.lineNumber(), cm.sourceId()));
        return true;
    }
}

How can I parse String to Int in an Angular expression?

I prefer to use an angular filter.

app.filter('num', function() {
    return function(input) {
      return parseInt(input, 10);
    };
});

then you can use this in the dom:

{{'10'|num}}

Here is a fiddle.

Hope this helped!

Validate IPv4 address in Java

This is for Android, testing for IPv4 and IPv6

Note: the commonly used InetAddressUtils is deprecated. Use new InetAddress classes

public static Boolean isIPv4Address(String address) {
    if (address.isEmpty()) {
        return false;
    }
    try {
        Object res = InetAddress.getByName(address);
        return res instanceof Inet4Address || res instanceof Inet6Address;
    } catch (final UnknownHostException exception) {
        return false;
    }
}

Why is 2 * (i * i) faster than 2 * i * i in Java?

Kasperd asked in a comment of the accepted answer:

The Java and C examples use quite different register names. Are both example using the AMD64 ISA?

xor edx, edx
xor eax, eax
.L2:
mov ecx, edx
imul ecx, edx
add edx, 1
lea eax, [rax+rcx*2]
cmp edx, 1000000000
jne .L2

I don't have enough reputation to answer this in the comments, but these are the same ISA. It's worth pointing out that the GCC version uses 32-bit integer logic and the JVM compiled version uses 64-bit integer logic internally.

R8 to R15 are just new X86_64 registers. EAX to EDX are the lower parts of the RAX to RDX general purpose registers. The important part in the answer is that the GCC version is not unrolled. It simply executes one round of the loop per actual machine code loop. While the JVM version has 16 rounds of the loop in one physical loop (based on rustyx answer, I did not reinterpret the assembly). This is one of the reasons why there are more registers being used since the loop body is actually 16 times longer.

How to set Angular 4 background image?

You can use ngStyle to set background for a div

<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>

or you can also use built in background style:

<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>

Using Java 8 to convert a list of objects into a string obtained from the toString() method

Just in case anyone is trying to do this without java 8, there is a pretty good trick. List.toString() already returns a collection that looks like this:

[1,2,3]

Depending on your specific requirements, this can be post-processed to whatever you want as long as your list items don't contain [] or , .

For instance:

list.toString().replace("[","").replace("]","") 

or if your data might contain square brackets this:

String s=list.toString();
s = s.substring(1,s.length()-1) 

will get you a pretty reasonable output.

One array item on each line can be created like this:

list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")

I used this technique to make html tooltips from a list in a small app, with something like:

list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")

If you have an array then start with Arrays.asList(list).toString() instead

I'll totally own the fact that this is not optimal, but it's not as inefficient as you might think and is pretty straightforward to read and understand. It is, however, quite inflexible--in particular don't try to separate the elements with replaceAll if your data might contain commas and use the substring version if you have square brackets in your data, but for an array of numbers it's pretty much perfect.

PHP Array to JSON Array using json_encode();

I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:

$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");

It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.

Hope that helps

What are allowed characters in cookies?

There is another interesting issue with IE and Edge. Cookies that have names with more than 1 period seem to be silently dropped. So This works:

cookie_name_a=valuea

while this will get dropped

cookie.name.a=valuea

How to use getJSON, sending data with post method?

This is my "one-line" solution:

$.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }

In order to use jsonp, and POST method, this function adds the "callback" GET parameter to the URL. This is the way to use it:

$.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
   console.log(data.name);
});

The server must be prepared to handle the callback GET parameter and return the json string as:

jsonp000000 ({"name":"John", "age": 25});

in which "jsonp000000" is the callback GET value.

In PHP the implementation would be like:

print_r($_GET['callback']."(".json_encode($myarr).");");

I made some cross-domain tests and it seems to work. Still need more testing though.

Git on Mac OS X v10.7 (Lion)

If you do not want to install Xcode and/or MacPorts/Fink/Homebrew, you could always use the standalone installer: https://sourceforge.net/projects/git-osx-installer/

iPad/iPhone hover problem causes the user to double click a link

You can use click touchend ,

example:

$('a').on('click touchend', function() {
    var linkToAffect = $(this);
    var linkToAffectHref = linkToAffect.attr('href');
    window.location = linkToAffectHref;
});

Above example will affect all links on touch devices.

If you want to target only specific links, you can do this by setting a class on them, ie:

HTML:

<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>

Jquery:

$('a.prevent-extra-click').on('click touchend', function() {
    var linkToAffect = $(this);
    var linkToAffectHref = linkToAffect.attr('href');
    window.location = linkToAffectHref;
});

Cheers,

Jeroen

Removing all non-numeric characters from string in Python

Just to add another option to the mix, there are several useful constants within the string module. While more useful in other cases, they can be used here.

>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

There are several constants in the module, including:

  • ascii_letters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
  • hexdigits (0123456789abcdefABCDEF)

If you are using these constants heavily, it can be worthwhile to covert them to a frozenset. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.

>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

Why should I use the keyword "final" on a method parameter in Java?

Yes, excluding anonymous classes, readability and intent declaration it's almost worthless. Are those three things worthless though?

Personally I tend not to use final for local variables and parameters unless I'm using the variable in an anonymous inner class, but I can certainly see the point of those who want to make it clear that the parameter value itself won't change (even if the object it refers to changes its contents). For those who find that adds to readability, I think it's an entirely reasonable thing to do.

Your point would be more important if anyone were actually claiming that it did keep data constant in a way that it doesn't - but I can't remember seeing any such claims. Are you suggesting there's a significant body of developers suggesting that final has more effect than it really does?

EDIT: I should really have summed all of this up with a Monty Python reference; the question seems somewhat similar to asking "What have the Romans ever done for us?"

What are the differences between normal and slim package of jquery?

I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):

  • After sending an email the global variables get stuck, and that makes if the user gives f5 (reload page) it is sent again. min:
  • The previous error will be solved. how i suffered!

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

Best way to store chat messages in a database?

If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.

Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure

Here's a simplified view of the file structure:

chat-1-bob.txt
        201101011029, hi
        201101011030, fine thanks.

chat-1-jen.txt
        201101011030, how are you?
        201101011035, have you spoken to bill recently?

chat-2-bob.txt
        201101021200, hi
        201101021222, about 12:22
chat-2-bill.txt
        201101021201, Hey Bob,
        201101021203, what time do you call this?

You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.

I think you will find it hard to get a more simple scaleable solution.

You can use LOAD_FILE to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

How to catch all exceptions in c# using try and catch?

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

Remove the legend on a matplotlib figure

you have to add the following lines of code:

ax = gca()
ax.legend_ = None
draw()

gca() returns the current axes handle, and has that property legend_

force css grid container to fill full screen of device

You can add position: fixed; with top left right bottom 0 attribute, that solution work on older browsers too.

If you want to embed it, add position: absolute; to the wrapper, and position: relative to the div outside of the wrapper.

_x000D_
_x000D_
.wrapper {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How should I pass an int into stringWithFormat?

Don't forget for long long int:

long long int id = [obj.id longLongValue];
[NSString stringWithFormat:@"this is my id: %lld", id]

Regex: match everything but specific pattern

Regex: match everything but:

Demo note: the newline \n is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.

Anchor note: In many languages, use \A to define the unambiguous start of string, and \z (in Python, it is \Z, in JavaScript, $ is OK) to define the very end of the string.

Dot note: In many flavors (but not POSIX, TRE, TCL), . matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s in PCRE/Boost/.NET/Python/Java and /m in Ruby) for the . to match any char including a newline.

Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\. will be declared as "world\\.", or use a character class: "world[.]"). Use raw string literals (Python r'\bworld\b'), C# verbatim string literals @"world\.", or slashy strings/regex literal notations like /world\./.

How does one remove a Docker image?

Why nobody mentioned docker-compose! I 've just been using it for one week, and I cannot survive without it. All you need is writing a yml which takes only several minutes of studying, and then you are ready to go. It can boot images, containers (which are needed in so-called services) and let you review logs just like you use with docker native commands. Git it a try:

docker-compose up -d
docker-compose down --rmi 'local'

Before I used docker-compose, I wrote my own shell script, then I had to customize the script whenever needed especially when application architecture changed. Now I don't have to do this anymore, thanks to docker-compose.

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

Importing large sql file to MySql via command line

Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...

First open MySQL:

mysql -u root -p

Then, You just need to do following :

mysql>use your_db

mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;

req.body empty on posts

Change app.use(bodyParser.urlencoded()); in your code to

app.use(bodyParser.urlencoded({extended : false}));

and in postman, in header change Content-Type value from application/x-www-form-urlencoded to application/json

Ta:-)

is there a tool to create SVG paths from an SVG file?

Open the svg using Inkscape.

Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/

  • ctrl A (select all)
  • shift ctrl C (=Path/Object to paths)
  • ctrl s (save (choose as plain svg))

done

all rect/circle have been converted to path

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

Try this code:

CONVERT(varchar(15), date_started, 103)

"Continue" (to next iteration) on VBScript

A solution I decided on involved the use of a boolean variable to track if the for loop should process its instructions or skip to the next iteration:

Dim continue

For Each item In collection
    continue = True

    If condition1 Then continue = False End If

    If continue Then
        'Do work
    End If
Next

I found the nested loop solutions to be somewhat confusing readability wise. This method also has its own pitfalls since the loop doesn't immediately skip to the next iteration after encountering continue. It would be possible for a later condition to reverse the state of continue. It also has a secondary construct within the initial loop, and requires the declaration of an extra var.

Oh, VBScript...sigh.

Also, if you want to use the accepted answer, which isn't too bad readability wise, you could couple that with the use of : to merge the two loops into what appears to be one:

Dim i

For i = 0 To 10 : Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False : Next

I found it useful to eliminate the extra level of indentation.

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

Could not open input file: artisan

Most probably you are not in the right directory!

How to debug external class library projects in visual studio?

I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:

Build Events:

  • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

  • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

Debug:

  • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

  • Working Directory C:\<path-to-main>\bin\debug

This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

How to trim white space from all elements in array?

I know this is a really old post, but since Java 1.8 there is a nicer way to trim every String in an array.

Java 8 Lamda Expression solution:

List<String> temp = new ArrayList<>(Arrays.asList(yourArray));
temp.forEach(e -> {temp.set((temp.indexOf(e), e.trim()});
yourArray = temp.toArray(new String[temp.size()]);

with this solution you don't have to create a new Array.
Like in Óscar López's solution

Division of integers in Java

You don't even need doubles for this. Just multiply by 100 first and then divide. Otherwise the result would be less than 1 and get truncated to zero, as you saw.

edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

AngularJS ng-click stopPropagation

<ul class="col col-double clearfix">
 <li class="col__item" ng-repeat="location in searchLocations">
   <label>
    <input type="checkbox" ng-click="onLocationSelectionClicked($event)" checklist-model="selectedAuctions.locations" checklist-value="location.code" checklist-change="auctionSelectionChanged()" id="{{location.code}}"> {{location.displayName}}
   </label>



$scope.onLocationSelectionClicked = function($event) {
      if($scope.limitSelectionCountTo &&         $scope.selectedAuctions.locations.length == $scope.limitSelectionCountTo) {
         $event.currentTarget.checked=false;
      }
   };

Launch custom android application from android browser

For example, You have next things:

A link to open your app: http://example.com

The package name of your app: com.example.mypackage

Then you need to do next:

  1. Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).

    <activity
         android:name=".MainActivity">
    
         <intent-filter android:label="@string/filter_title_view_app_from_web">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <!-- Accepts URIs that begin with "http://example.com" -->
    
             <data
                 android:host="example.com"
                 android:scheme="http" />
         </intent-filter>
    
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
    
     </activity> 
    
  2. Create a HTML file to test the link or use this methods.

    Open your Activity directly (just open your Activity, without a choosing dialog).

    Open this link with browser or your programm (by choosing dialog).

  3. Use Mobile Chrome to test

  4. That's it.

And its not necessary to publish app in market to test deep linking =)

Also, for more information, check documentation and useful presentation.

How to generate a random string of 20 characters

You may use the class java.util.Random with method

char c = (char)(rnd.nextInt(128-32))+32 

20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.

32 is the offset, from where the characters are printable in general.

ASP.NET strange compilation error

I had to kill multiple instances of MSBuild.exe hanging in process explorer.

Then the website runs OK.

How to convert LINQ query result to List?

You need to use the select new LINQ keyword to explicitly convert your tbcourseentity into the custom type course. Example of select new:

var q = from o in db.Orders
        where o.Products.ProductName.StartsWith("Asset") && 
              o.PaymentApproved == true
        select new { name   = o.Contacts.FirstName + " " +
                              o.Contacts.LastName, 
                     product = o.Products.ProductName, 
                     version = o.Products.Version + 
                              (o.Products.SubVersion * 0.1)
                   };

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

How to create a JQuery Clock / Timer

################## JQuery (use API) #################   
 $(document).ready(function(){
         function getdate(){
                var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
             if(s<10){
                 s = "0"+s;
             }
             if (m < 10) {
                m = "0" + m;
            }
            $("h1").text(h+" : "+m+" : "+s);
             setTimeout(function(){getdate()}, 500);
            }

        $("button").click(getdate);
    });

################## HTML ###################
<button>start clock</button>
<h1></h1>

How to select an item in a ListView programmatically?

ListViewItem.IsSelected = true;
ListViewItem.Focus();

remove table row with specific id

Simply $("#3").remove(); would be enough. But 3 isn't a good id (I think it's even illegal, as it starts with a digit).

How do I connect to this localhost from another computer on the same network?

If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:

Listen: 10.20.30.40:80

Restart your Apache server and test it from other computer on the network.

How to generate all permutations of a list?

from typing import List
import time, random

def measure_time(func):
    def wrapper_time(*args, **kwargs):
        start_time = time.perf_counter()
        res = func(*args, **kwargs)
        end_time = time.perf_counter()
        return res, end_time - start_time

    return wrapper_time


class Solution:
    def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:
        perms = []
        perm = []
        if method == 1:
            _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)
        elif method == 2:
            _, time_perm = self._permute_recur_agian(nums, perm, perms)
            print(perm)
        return perms, time_perm

    @measure_time
    def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):
        # base case
        if l == r:
            perms.append(nums.copy())

        for i in range(l, r + 1):
            nums[l], nums[i] = nums[i], nums[l]
            self._permute_recur(nums, l + 1, r , perms)
            nums[l], nums[i] = nums[i], nums[l]

    @measure_time
    def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):
        """
        The idea is similar to nestedForLoops visualized as a recursion tree.
        """
        if nums:
            for i in range(len(nums)):
                # perm.append(nums[i])  mistake, perm will be filled with all nums's elements.
                # Method1 perm_copy = copy.deepcopy(perm)
                # Method2 add in the parameter list using + (not in place)
                # caveat: list.append is in-place , which is useful for operating on global element perms_list
                # Note that:
                # perms_list pass by reference. shallow copy
                # perm + [nums[i]] pass by value instead of reference.
                self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)
        else:
            # Arrive at the last loop, i.e. leaf of the recursion tree.
            perms_list.append(perm)



if __name__ == "__main__":
    array = [random.randint(-10, 10) for _ in range(3)]
    sol = Solution()
    # perms, time_perm = sol.permute(array, 1)
    perms2, time_perm2 = sol.permute(array, 2)
    print(perms2)
    # print(perms, perms2)
    # print(time_perm, time_perm2)
```

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

Why do I get the "Unhandled exception type IOException"?

I got the Error even though i was catching the exception.

    try {
        bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
    } catch (IOException e) {
        Log.e("blabla", "Error", e);
        finish();
    }

Issue was that the IOException wasn't imported

import java.io.IOException;

Response to preflight request doesn't pass access control check

In PHP you can add the headers:

<?php
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: *");
...

How do I prevent a Gateway Timeout with FastCGI on Nginx

In http nginx section (/etc/nginx/nginx.conf) add or modify:

keepalive_timeout 300s

In server nginx section (/etc/nginx/sites-available/your-config-file.com) add these lines:

client_max_body_size 50M;
fastcgi_buffers 8 1600k;
fastcgi_buffer_size 3200k;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;

In php file in the case 127.0.0.1:9000 (/etc/php/7.X/fpm/pool.d/www.conf) modify:

request_terminate_timeout = 300

I hope help you.

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

If you can not authenticate via the web interface (localhost/phpmyadmin/) then try change authentication type to cookie.

$cfg['Servers'][$i]['auth_type'] = 'cookie';

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.

What is the Regular Expression For "Not Whitespace and Not a hyphen"

[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.

ImportError: No module named xlsxwriter

I have the same issue. It seems that pip is the problem. Try

pip uninstall xlsxwriter
easy_install xlsxwriter

Convert unsigned int to signed int C

I know this is an old question, but I think the responders may have misinterpreted it. I think what was intended was to convert a 16-digit bit sequence received as an unsigned integer (technically, an unsigned short) into a signed integer. This might happen (it recently did to me) when you need to convert something received from a network from network byte order to host byte order. In that case, use a union:

unsigned short value_from_network;
unsigned short host_val = ntohs(value_from_network);
// Now suppose host_val is 65529.
union SignedUnsigned {
  short          s_int;
  unsigned short us_int;
};
SignedUnsigned su;
su.us_int = host_val;
short minus_seven = su.s_int;

And now minus_seven has the value -7.

How can I open Windows Explorer to a certain directory from within a WPF app?

You can use System.Diagnostics.Process.Start.

Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.

public partial class Window1 : Window
{
    public Window1()
    {
        ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
        InitializeComponent();
    }

    public enum ShowCommands : int
    {
        SW_HIDE = 0,
        SW_SHOWNORMAL = 1,
        SW_NORMAL = 1,
        SW_SHOWMINIMIZED = 2,
        SW_SHOWMAXIMIZED = 3,
        SW_MAXIMIZE = 3,
        SW_SHOWNOACTIVATE = 4,
        SW_SHOW = 5,
        SW_MINIMIZE = 6,
        SW_SHOWMINNOACTIVE = 7,
        SW_SHOWNA = 8,
        SW_RESTORE = 9,
        SW_SHOWDEFAULT = 10,
        SW_FORCEMINIMIZE = 11,
        SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(
        IntPtr hwnd,
        string lpOperation,
        string lpFile,
        string lpParameters,
        string lpDirectory,
        ShowCommands nShowCmd);
}

The declarations come from the pinvoke.net website.

Using Apache httpclient for https

This is what worked for me:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "password".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

What is an AssertionError? In which case should I throw it from my own code?

Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw AssertionErrors everywhere, and that is obviously not what happens.

The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private and not calling it from within Example's code). And so if a call occurs, that assertion has been violated, and so AssertionError is appropriate.

How to switch a user per task or set of tasks?

In Ansible 2.x, you can use the block for group of tasks:

- block:
    - name: checkout repo
      git:
        repo: https://github.com/some/repo.git
        version: master
        dest: "{{ dst }}"
    - name: change perms
      file:
      dest: "{{ dst }}"
      state: directory
      mode: 0755
      owner: some_user
  become: yes
  become_user: some user

How to check if a process is running via a batch script

I used the script provided by Matt (2008-10-02). The only thing I had trouble with was that it wouldn't delete the search.log file. I expect because I had to cd to another location to start my program. I cd'd back to where the BAT file and search.log are, but it still wouldn't delete. So I resolved that by deleting the search.log file first instead of last.

del search.log

tasklist /FI "IMAGENAME eq myprog.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%-zA EQU 0 GOTO end

cd "C:\Program Files\MyLoc\bin"

myprog.exe myuser mypwd

:end

Spring - @Transactional - What happens in background?

As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client executes Proxy.method().

  1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
  2. If a before aspect is defined, the proxy will execute it
  3. Then, the actual method (target) is executed
  4. After-returning and after-throwing are optional aspects that are executed after the method returns and/or if the method throws an exception
  5. After that, the proxy executes the after aspect (if defined)
  6. Finally the proxy returns to the calling client

Proxy Pattern Sequence Diagram (I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

Python try-else

I find it really useful when you've got cleanup to do that has to be done even if there's an exception:

try:
    data = something_that_can_go_wrong()
except Exception as e: # yes, I know that's a bad way to do it...
    handle_exception(e)
else:
    do_stuff(data)
finally:
    clean_up()

Calling another different view from the controller using ASP.NET MVC 4

            public ActionResult Index()
            {
                return View();
            }


            public ActionResult Test(string Name)
            {
                return RedirectToAction("Index");
            }

Return View Directly displays your view but

Redirect ToAction Action is performed

How do I get the path of the current executed file in Python?

The short answer is that there is no guaranteed way to get the information you want, however there are heuristics that work almost always in practice. You might look at How do I find the location of the executable in C?. It discusses the problem from a C point of view, but the proposed solutions are easily transcribed into Python.

Rotating and spacing axis labels in ggplot2

To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to

q + theme(axis.text.x=element_text(angle=90, hjust=1))

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

The project description file (.project) for my project is missing

I created a new workspace and imported old projects. I just didn’t open this workspace for a long time, I don’t know why this problem happened

How to create a DataFrame from a text file in Spark

You can read a file to have an RDD and then assign schema to it. Two common ways to creating schema are either using a case class or a Schema object [my preferred one]. Follows the quick snippets of code that you may use.

Case Class approach

case class Test(id:String,name:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Schema Approach

import org.apache.spark.sql.types._
val schemaString = "id name"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header","false").schema(schema).csv("file.txt")
dfWithSchema.show()

The second one is my preferred approach since case class has a limitation of max 22 fields and this will be a problem if your file has more than 22 fields!

Android SeekBar setOnSeekBarChangeListener

I hope this will help you:

final TextView t1=new TextView(this); 
t1.setText("Hello Android");        
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);     
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

    @Override       
    public void onStopTrackingTouch(SeekBar seekBar) {      
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onStartTrackingTouch(SeekBar seekBar) {     
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
        // TODO Auto-generated method stub      

        t1.setTextSize(progress);
        Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();

    }       
});             

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This exception could point to the LINQ parameter that is named source:

 System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)

As the source parameter in your LINQ query (var nCounts = from sale in sal) is 'sal', I suppose the list named 'sal' might be null.

Creating a textarea with auto-resize

Just use <pre> </pre> with some styles like:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }

Bootstrap select dropdown list placeholder

Try @title = "stuff". It worked for me.

Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

    namespace PingTest1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

Call Python function from MATLAB

Starting from Matlab 2014b Python functions can be called directly. Use prefix py, then module name, and finally function name like so:

result = py.module_name.function_name(parameter1);

Make sure to add the script to the Python search path when calling from Matlab if you are in a different working directory than that of the Python script.

See more details here.

Print Combining Strings and Numbers

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

print "First number is {} and second number is {}".format(first, second)

How do I clear all options in a dropdown box?

The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null, as that may cause unexpected behaviour.

var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
    select.remove(i);

Or if you prefer, you can make it a function:

function clearOptions(id)
{
    var select = document.getElementById(id);
    for (var i = select.options.length - 1 ; i >= 0 ; i--)
        select.remove(i);
}
clearOptions("myselect");

Reading a file character by character in C

Expanding upon the above code from @dreamlax

char *readFile(char *fileName) {
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL) return NULL; //could not open file
    fseek(file, 0, SEEK_END);
    long f_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    code = malloc(f_size);

    while ((c = fgetc(file)) != EOF) {
        code[n++] = (char)c;
    }

    code[n] = '\0';        

    return code;
}

This gives you the length of the file, then proceeds to read it character by character.

Facebook Like-Button - hide count?

Most of the suggestions are now, no longer valid.

The correct fix as of today, is to use the 'button' layout.

eg. <div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button" data-action="like" data-show-faces="true" data-share="false"></div>

Image of button on FB Docs

The FB Docs, seem not to be fully updated yet... if you scroll down you'll see they state only 3 layouts are available, yet the dropdown suggests 4.

enter image description here

This means you can now use a less hacky solution!

To get specific part of a string in c#

Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split:

string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);

Output:

abc

Set up Python 3 build system with Sublime Text 3

Steps for configuring Sublime Text Editor3 for Python3 :-

  1. Go to preferences in the toolbar.
  2. Select Package Control.
  3. A pop up will open.
  4. Type/Select Package Control:Install Package.
  5. Wait for a minute till repositories are loading.
  6. Another Pop up will open.
  7. Search for Python 3.
  8. Now sublime text is set for Python3.
  9. Now go to Tools-> Build System.
  10. Select Python3.

Enjoy Coding.

How do you get the file size in C#?

The FileInfo class' Length property returns the size of the file (not the size on disk). If you want a formatted file size (i.e. 15 KB) rather than a long byte value you can use CSharpLib, a package I've made that adds more functionality to the FileInfo class. Here's an example:

using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes());  // Output: 15 MB

How do I control how Emacs makes backup files?

Emacs backup/auto-save files can be very helpful. But these features are confusing.

Backup files

Backup files have tildes (~ or ~9~) at the end and shall be written to the user home directory. When make-backup-files is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file.

No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below).

To create backups explicitly use save-buffer (C-x C-s) with prefix arguments.

diff-backup and dired-diff-backup compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file

C:\Users\USERNAME\.emacs.d\backups\!drive_c!Users!USERNAME!.emacs.el.~7~

it has to be manually copied as

C:\Users\USERNAME\.emacs.el

Auto-save files

Auto-save files use hashmarks (#) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience).

  • Before the user presses C-x C-s (save-buffer) to save a file Emacs auto-saves files - based on counting keystrokes (auto-save-interval) or when you stop typing (auto-save-timeout).
  • Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command.

When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist.

Use revert-buffer or recover-file to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named ~/.emacs.d/auto-save-list. The recover-session function will use this information.

The preferred method to recover from an auto-saved filed is M-x revert-buffer RET. Emacs will ask either "Buffer has been auto-saved recently. Revert from auto-save file?" or "Revert buffer from file FILENAME?". In case of the latter there is no auto-save file. For example, because you have saved before typing another auto-save-intervall keystrokes, in which case Emacs had deleted the auto-save file.

Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.

Configuration

Here is a configuration that IMHO works best:

(defvar --backup-directory (concat user-emacs-directory "backups"))
(if (not (file-exists-p --backup-directory))
        (make-directory --backup-directory t))
(setq backup-directory-alist `(("." . ,--backup-directory)))
(setq make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash t
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

Sensitive data

Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use this mode on a per-file basis. As this is a minor mode, for my purposes I renamed it sensitive-minor-mode.

To enable it for all .vcf and .gpg files, in your .emacs use something like:

(setq auto-mode-alist
      (append
       (list
        '("\\.\\(vcf\\|gpg\\)$" . sensitive-minor-mode)
        )
       auto-mode-alist))

Alternatively, to protect only some files, like some .txt files, use a line like

// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-

in the file.

Class extending more than one class Java?

Java does not allow extending multiple classes.

Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:

C obj1 = new C(); obj1.method1(); - here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.

Hope this has helped.

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

How to set the text color of TextView in code?

There are many different ways to set color on text view.

  1. Add color value in studio res->values->colors.xml as

    <color name="color_purple">#800080</color>
    

    Now set the color in xml or actvity class as

    text.setTextColor(getResources().getColor(R.color.color_purple)
    
  2. If you want to give color code directly use below Color.parseColor code

    textView.setTextColor(Color.parseColor("#ffffff"));   
    
  3. You can also use RGB

    text.setTextColor(Color.rgb(200,0,0));
    
  4. Use can also use direct hexcode for textView. You can also insert plain HEX, like so:

    text.setTextColor(0xAARRGGBB);
    
  5. You can also use argb with alpha values.

       text.setTextColor(Color.argb(0,200,0,0));
    

    a for Alpha (Transparent) v.

  6. And if you're using the Compat library you can do something like this

       text.setTextColor(ContextCompat.getColor(context, R.color.color_purple));
    

How to remove all files from directory without removing directory in Node.js

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.clear(); // <--

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

Best way to get user GPS location in background in Android

Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.concurrent.TimeUnit;

/**
 * Created by Ketan Ramani on 05/11/18.
 */

public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    /* Declare in manifest
    <service android:name=".BackgroundLocationUpdateService"/>
    */

    private final String TAG = "BackgroundLocationUpdateService";
    private final String TAG_LOCATION = "TAG_LOCATION";
    private Context context;
    private boolean stopService = false;

    /* For Google Fused API */
    protected GoogleApiClient mGoogleApiClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    private String latitude = "0.0", longitude = "0.0";
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationCallback mLocationCallback;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    /* For Google Fused API */

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        StartForeground();
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    if (!stopService) {
                        //Perform your task here
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (!stopService) {
                        handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
                    }
                }
            }
        };
        handler.postDelayed(runnable, 2000);

        buildGoogleApiClient();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service Stopped");
        stopService = true;
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            Log.e(TAG_LOCATION, "Location Update Callback Removed");
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void StartForeground() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        String CHANNEL_ID = "channel_location";
        String CHANNEL_NAME = "channel_location";

        NotificationCompat.Builder builder = null;
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
            builder.setChannelId(CHANNEL_ID);
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        }

        builder.setContentTitle("Your title");
        builder.setContentText("You are now online");
        Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_logo);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        startForeground(101, notification);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());

        latitude = String.valueOf(location.getLatitude());
        longitude = String.valueOf(location.getLongitude());

        if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
            requestLocationUpdate();
        } else {
            Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();

        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        Log.e(TAG_LOCATION, "GPS Success");
                        requestLocationUpdate();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            int REQUEST_CHECK_SETTINGS = 214;
                            ResolvableApiException rae = (ResolvableApiException) e;
                            rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sie) {
                            Log.e(TAG_LOCATION, "Unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
                }
            }
        }).addOnCanceledListener(new OnCanceledListener() {
            @Override
            public void onCanceled() {
                Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
            }
        });
    }

    @Override
    public void onConnectionSuspended(int i) {
        connectGoogleClient();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        mSettingsClient = LocationServices.getSettingsClient(context);

        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        connectGoogleClient();

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Log.e(TAG_LOCATION, "Location Received");
                mCurrentLocation = locationResult.getLastLocation();
                onLocationChanged(mCurrentLocation);
            }
        };
    }

    private void connectGoogleClient() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
        if (resultCode == ConnectionResult.SUCCESS) {
            mGoogleApiClient.connect();
        }
    }

    @SuppressLint("MissingPermission")
    private void requestLocationUpdate() {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }
}

In Activity

Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));

Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));

In Fragment

Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));

Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));

A cycle was detected in the build path of project xxx - Build Path Problem

I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree

Selecting a row of pandas series/dataframe by integer index

I would normally go for .loc/.iloc as suggested by Ted, but one may also select a row by tranposing the DataFrame. To stay in the example above, df.T[2] gives you row 2 of df.

What is the difference between Collection and List in Java?

Collection is the root interface to the java Collections hierarchy. List is one sub interface which defines an ordered Collection, other sub interfaces are Queue which typically will store elements ready for processing (e.g. stack).

The following diagram demonstrates the relationship between the different java collection types:

java collections

How do you set EditText to only accept numeric values in Android?

I don't know what the correct answer was in '13, but today it is:

myEditText.setKeyListener(DigitsKeyListener.getInstance(null, false, true)); // positive decimal numbers

You get everything, including the onscreen keyboard is a numeric keypad.

ALMOST everything. Espresso, in its infinite wisdom, lets typeText("...") inexplicably bypass the filter and enter garbage...

Namenode not getting started

I got the solution just share with you that will work who got the errors:

1. First check the /home/hadoop/etc/hadoop path, hdfs-site.xml and

 check the path of namenode and datanode 

<property>
  <name>dfs.name.dir</name>
    <value>file:///home/hadoop/hadoopdata/hdfs/namenode</value>
</property>

<property>
  <name>dfs.data.dir</name>
    <value>file:///home/hadoop/hadoopdata/hdfs/datanode</value>
</property>

2.Check the permission,group and user of namenode and datanode of the particular path(/home/hadoop/hadoopdata/hdfs/datanode), and check if there are any problems in all of them and if there are any mismatch then correct it. ex .chown -R hadoop:hadoop in_use.lock, change user and group

chmod -R 755 <file_name> for change the permission

How can I use the HTML5 canvas element in IE?

You can try fxCanvas: https://code.google.com/p/fxcanvas/

It implements almost all Canvas API within flash shim.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

It's permission problem. It is not "classic" read/write permissions of apache user, but selinux one.

Apache cannot write to files labeled as httpd_sys_content_t they can be only read by apache.

You have 2 possibilities:

  1. label svn repository files as httpd_sys_content_rw_t:

    chcon -R -t httpd_sys_content_rw_t /path/to/your/svn/repo
    
  2. set selinux boolean httpd_unified --> on

    setsebool -P httpd_unified=1
    

I prefer 2nd possibility. You can play also with other selinux booleans connected with httpd:

getsebool -a | grep httpd

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

How do I validate a date in rails?

A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:

Inside your model.rb

validate :date_field_must_be_a_date_or_blank

# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
  date_field_before_type_cast.to_date
rescue ArgumentError
  errors.add(:birthday, :invalid)
end

Custom HTTP Authorization Header

Old question I know, but for the curious:

Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)

You could do the same, so that the example above would become:

Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==

Git: How to remove remote origin from Git repo

perhaps I am late you can use git remote remove origin it will do the job.

Verify External Script Is Loaded

@jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:

function isScriptLoaded(src)
{
    return document.querySelector('script[src="' + src + '"]') ? true : false;
}

final keyword in method parameters

If you declare any parameter as final, you cannot change the value of it.

class Bike11 {  
    int cube(final int n) {  
        n=n+2;//can't be changed as n is final  
        n*n*n;  
     }  
    public static void main(String args[]) {  
        Bike11 b=new Bike11();  
        b.cube(5);  
    }  
}   

Output: Compile Time Error

For more details, please visit my blog: http://javabyroopam.blogspot.com

Create PostgreSQL ROLE (user) if it doesn't exist

The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

Workaround from within psql

SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec

Workaround from the shell

echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql

See accepted answer there for more details.

SQL Server loop - how do I loop through a set of records

I think this is the easy way example to iterate item.

declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'

while (select count(*) from #TempTable) > 0
begin
    select top 1 @cateid = CateID from #TempTable
    print(@cateid)

    --DO SOMETHING HERE

    delete #TempTable where CateID = @cateid
end

drop table #TempTable

How to download PDF automatically using js?

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);

Fixed Table Cell Width

Now in HTML5/CSS3 we have better solution for the problem. In my opinion this purely CSS solution is recommended:

_x000D_
_x000D_
table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/_x000D_
table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/_x000D_
table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/_x000D_
table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/_x000D_
table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
_x000D_
<table class="fixed">_x000D_
    <tr>_x000D_
        <td>Veryverylongtext</td>_x000D_
        <td>Actuallythistextismuchlongeeeeeer</td>_x000D_
        <td>We should use spaces tooooooooooooo</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You need to set the table's width even in haunter's solution. Otherwise it doesn't work.
Also a new CSS3 feature that vsync suggested is: word-break:break-all;. This will break the words without spaces in them to multiple lines too. Just modify the code like this:

table.fixed { table-layout:fixed; width:90px; word-break:break-all;}

Final result

Rendered table

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Add

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
));

before

mail->send()

and replace

require "mailer/class.phpmailer.php";

with

require "mailer/PHPMailerAutoload.php";

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

Android: How to change CheckBox size?

You just need to set the related drawables and set them in the checkbox:

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

The trick is on how to set the drawables. Here's a good tutorial about this.

How to iterate over each string in a list of strings and operate on it's elements

Use range() instead, like the following :

for i in range(len(words)):
    ...

Delete file from internal storage

Have you tried getFilesDir().getAbsolutePath()?

Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.

Check for special characters (/*-+_@&$#%) in a string?

Try this way.

public static bool hasSpecialChar(string input)
    {
        string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
        foreach (var item in specialChar)
        {
            if (input.Contains(item)) return true;
        }

        return false;
    }

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.

The one I've just found and I could absolutely recommend is The Uniform Server

It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.

They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!

Versions in Uniform Server as of today:

  • Apache 2.4.2
  • MySQL 5.5.23-community
  • PHP 5.4.1
  • phpMyAdmin 3.5.0

Versions in XAMPP as of today:

  • Apache 2.2.21
  • MySQL 5.5.16
  • PHP 5.3.8
  • phpMyAdmin 3.4.5

How to return dictionary keys as a list in Python?

Python >= 3.5 alternative: unpack into a list literal [*newdict]

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop

%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop

%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}

beware of the trailing comma in the tuple case!

TLS 1.2 not working in cURL

You must use an integer value for the CURLOPT_SSLVERSION value, not a string as listed above

Try this:

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2

http://php.net/manual/en/function.curl-setopt.php

value should be an integer for the following values of the option parameter: CURLOPT_SSLVERSION

One of

CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).

Jenkins "Console Output" log location in filesystem

Easy solution would be:

curl  http://jenkinsUrl/job/<Build_Name>/<Build_Number>/consoleText -OutFile <FilePathToLocalDisk>

or for the last successful build...

curl  http://jenkinsUrl/job/<Build_Name>/lastSuccessfulBuild/consoleText -OutFile <FilePathToLocalDisk>

What is perm space?

Perm Gen stands for permanent generation which holds the meta-data information about the classes.

  1. Suppose if you create a class name A, it's instance variable will be stored in heap memory and class A along with static classloaders will be stored in permanent generation.
  2. Garbage collectors will find it difficult to clear or free the memory space stored in permanent generation memory. Hence it is always recommended to keep the permgen memory settings to the advisable limit.
  3. JAVA8 has introduced the concept called meta-space generation, hence permgen is no longer needed when you use jdk 1.8 versions.

How to install a specific version of a ruby gem?

Use the -v flag:

$ gem install fog -v 1.8

Can you split a stream into two streams?

I stumbled across this question while looking for a way to filter certain elements out of a stream and log them as errors. So I did not really need to split the stream so much as attach a premature terminating action to a predicate with unobtrusive syntax. This is what I came up with:

public class MyProcess {
    /* Return a Predicate that performs a bail-out action on non-matching items. */
    private static <T> Predicate<T> withAltAction(Predicate<T> pred, Consumer<T> altAction) {
    return x -> {
        if (pred.test(x)) {
            return true;
        }
        altAction.accept(x);
        return false;
    };

    /* Example usage in non-trivial pipeline */
    public void processItems(Stream<Item> stream) {
        stream.filter(Objects::nonNull)
              .peek(this::logItem)
              .map(Item::getSubItems)
              .filter(withAltAction(SubItem::isValid,
                                    i -> logError(i, "Invalid")))
              .peek(this::logSubItem)
              .filter(withAltAction(i -> i.size() > 10,
                                    i -> logError(i, "Too large")))
              .map(SubItem::toDisplayItem)
              .forEach(this::display);
    }
}