Programs & Examples On #Mobileme

MobileMe is Apple's cloud service for files, pictures, email, etc. on the web.

Detect if page has finished loading

One option is to have the page be blank, containing a small amount of javascript. Use the script to make an AJAX call to get the actual page content, and have the success function write the result over the current document. In the timeout function you can "do something else amazing"

Approximate pseudocode:

$(document).ready(function(){
    $.ajax
      url of actual page
      success:do something amazing
      timeout: do something else
});

laravel 5 : Class 'input' not found

In first your problem is about the spelling of the input class, should be Input instead of input. And you have to import the class with the good namespace.

use Illuminate\Support\Facades\Input;

If you want it called 'input' not 'Input', add this :

use Illuminate\Support\Facades\Input as input;

Second, It's a dirty way to store into the database via route.php, and you're not processing data validation. If a sent parameter isn't what you expected, maybe an SQL error will appear, its caused by the data type. You should use controller to interact with information and store via the model in the controller method.

The route.php file handles routing. It is designed to make the link between the controller and the asked route.

To learn about controller, middleware, model, service ... http://laravel.com/docs/5.1/

If you need some more information, solution about problem you can join the community : https://laracasts.com/

Regards.

Quotation marks inside a string

You can do this using Escape Sequence.

\"

So you will have to write something like this :

String name = "\"john\"";

You can learn about Escape Sequences from here.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Here is dirty way:

  1. Log into a linux server using "ssh -X user@host"
  2. open rxvt-unicode or other X terminal.
  3. open tmux or screen
  4. Log back into your local computer from the server
  5. start your favourite shell such as msys or cygwin.

how to disable DIV element and everything inside

You can't use "disable" to disable a click event. I don't know how or if it worked in IE6-9, but it didn't work on Chrome, and it shouldn't work on IE10 like that.

You can disable the onclick event, too, by attaching an event that cancels:

;(function () {
    function cancel () { return false; };
    document.getElementById("test").disabled = true;
    var nodes = document.getElementById("test").getElementsByTagName('*');
    console.log(nodes);
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].setAttribute('disabled', true);
        nodes[i].onclick = cancel;
    }
}());

Furthermore, setting "disabled" on a node directly doesn't necessarily add the attribute- using setAttribute does.

http://jsfiddle.net/2fPZu/

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

Hadoop/Hive : Loading data from .csv on a local machine

You can load local CSV file to Hive only if:

  1. You are doing it from one of the Hive cluster nodes.
  2. You installed Hive client on non-cluster node and using hive or beeline for upload.

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

jQuery form input select by id

For example like this:

var value = $("#a").find("#b").val()

pthread_join() and pthread_exit()

In pthread_exit, ret is an input parameter. You are simply passing the address of a variable to the function.

In pthread_join, ret is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL.

Long explanation:

In pthread_join, you get back the address passed to pthread_exit by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.

How to match "anything up until this sequence of characters" in a regular expression?

This will make sense about regex.

  1. The exact word can be get from the following regex command:

("(.*?)")/g

Here, we can get the exact word globally which is belonging inside the double quotes. For Example, If our search text is,

This is the example for "double quoted" words

then we will get "double quoted" from that sentence.

Print an integer in binary format in Java

The question is tricky in java (and probably also in other language).

A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.

So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).

The safe way is to use Integer.toString(X,2); this will generate something less elegant:

-11110100110

But it works!!!

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

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

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

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

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

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

{% url login.views.login_view %}

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Exit from app when click button in android phonegap?

if(navigator.app){
        navigator.app.exitApp();
}else if(navigator.device){
        navigator.device.exitApp();
}

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

How to start a stopped Docker container with a different command?

Add a check to the top of your Entrypoint script

Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.

If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh:

# Run once, hold otherwise
if [ -f "already_ran" ]; then
    echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
    cat
fi
touch already_ran

# Do your main things down here

To ensure that cat holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:

docker run -t --entrypoint entrypoint.sh image_name

This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:

docker start container_name

When you restart the container, the already_ran file will be found, causing the Entrypoint script to stall with cat (which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash session:

docker exec -i container_name bash

While the container is running, you can also remove already_ran and manually execute the entrypoint.sh script to rerun it, if you need to debug that way.

Flask-SQLalchemy update a row's information

This does not work if you modify a pickled attribute of the model. Pickled attributes should be replaced in order to trigger updates:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from pprint import pprint

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:////tmp/users.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.PickleType())

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()

# Create a user.
bob = User('Bob', {})
db.session.add(bob)
db.session.commit()

# Retrieve the row by its name.
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Modifying data is ignored.
bob.data['foo'] = 123
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Replacing data is respected.
bob.data = {'bar': 321}
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

# Modifying data is ignored.
bob.data['moo'] = 789
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

Remove First and Last Character C++

Well, you could erase() the first character too (note that erase() modifies the string):

m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);

But in this case, a simpler way is to take a substring:

m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);

Be careful to validate that the string actually has at least two characters in it first...

How to detect chrome and safari browser (webkit)

I am trying to detect the chrome and safari browser using jquery or javascript.

Use jQuery.browser

I thought we are not supposed to use jQuery.browser.

That's because detecting browsers is a bad idea. It is still the best way to detect the browser (when jQuery is involved) if you really intend to do that.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

How do you launch the JavaScript debugger in Google Chrome?

For Mac users, go to Google Chrome --> menu View --> Developer --> JavaScript Console.

Screenshot

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

How do I get the day of week given a date?

datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :

from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")

The output that you get from this is 'Mon'. If you want the output as 'Monday', use the following :

parser.parse('January 11, 2010').strftime("%A")

This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.

Python, remove all non-alphabet chars from string

You can use the re.sub() function to remove these characters:

>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'

re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)

  • "[^a-zA-Z]+" - look for any group of characters that are NOT a-zA-z.
  • "" - Replace the matched characters with ""

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

How to have a a razor action link open in a new tab?

Just use the HtmlHelper ActionLink and set the RouteValues and HtmlAttributes accordingly.

@Html.ActionLink(Reports.RunReport, "RunReport", new { controller = "Performance", reportView = Model.ReportView.ToString() }, new { target = "_blank" })

Parsing string as JSON with single quotes?

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);

This solved the problem for me.

Why does "return list.sort()" return None, not the list?

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).

How to drop a list of rows from Pandas dataframe?

I solved this in a simpler way - just in 2 steps.

  1. Make a dataframe with unwanted rows/data.

  2. Use the index of this unwanted dataframe to drop the rows from the original dataframe.

Example:
Suppose you have a dataframe df which as many columns including 'Age' which is an integer. Now let's say you want to drop all the rows with 'Age' as negative number.

df_age_negative = df[ df['Age'] < 0 ] # Step 1
df = df.drop(df_age_negative.index, axis=0) # Step 2

Hope this is much simpler and helps you.

Append text to textarea with javascript

Tray to add text with html value to textarea but it wil not works

value :

$(document).on('click', '.edit_targets_btn', function() {
            $('#add_edit_targets').modal('show');
            $('#add_edit_targets_form')[0].reset();
            $('#targets_modal_title').text('Doel bijwerken');
            $('#action').val('targets_update');
            $('#targets_submit_btn').val('Opslaan');

            $('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
            $('#targets_title').val($(this).attr("title"));
            $("#targets_content").append($(this).attr("content"));

            tinymce.init({
                selector: '#targets_content',
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                },
                browser_spellcheck : true,
                plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
                toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
                relative_urls : false,
                remove_script_host : false,
                image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
                min_height: 250,
                branding: false
            });
        });

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

How to convert Set<String> to String[]?

In Java 11 we can use Collection.toArray(generator) method. The following code will create a new array of String:

Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)

See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)

Git commit in terminal opens VIM, but can't get back to terminal

This is in answer to your question...

I'd also like to know how to make it open up in Sublime Text 2 instead

For Windows:

git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"

Check that the path for sublime_text.exe is correct and adjust if needed.

For Mac/Linux:

git config --global core.editor "subl -n -w"

If you get an error message such as:

error: There was a problem with the editor 'subl -n -w'.

Create the alias for subl

sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Again check that the path matches for your machine.

For Sublime Text simply save cmd S and close the window cmd W to return to git.

SVN commit command

To add a file/folder to the project, a good way is:

First of all add your files to /path/to/your/project/my/added/files, and then run following commands:

svn cleanup  /path/to/your/project

svn add --force /path/to/your/project/*

svn cleanup  /path/to/your/project

svn commit /path/to/your/project  -m 'Adding a file'

I used cleanup to prevent any segmentation fault (core dumped), and now the SVN project is updated.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

Logical XOR operator in C++?

(A || B) && !(A && B)

The first part is A OR B, which is the Inclusive OR; the second part is, NOT A AND B. Together you get A or B, but not both A and B.

This will provide the XOR proved in the truth table below.

|-----|-----|-----------|
|  A  |  B  |  A XOR B  |
|-----|-----|-----------|
|  T  |  T  |   False   |
|-----|-----|-----------|
|  T  |  F  |   True    |
|-----|-----|-----------|
|  F  |  T  |   True    |
|-----|-----|-----------|
|  F  |  F  |   False   |
|-----|-----|-----------|

How do I parse a string into a number with Dart?

you can parse string with int.parse('your string value');.

Example:- int num = int.parse('110011'); print(num); // prints 110011 ;

CSS image overlay with color and transparency

JSFiddle Demo

HTML:

<div class="image-holder">
    <img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>

CSS:

.image-holder {
    display:inline-block;
    position: relative;
}
.image-holder:after {
    content:'';
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    background: blue;
    opacity: 0.1;
}
.image-holder:hover:after {
    opacity: 0;
}

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

What is null in Java?

Short and precise answer which answers all your questions formally from JLS:

3.10.7. The Null Literal

The null type has one value, the null reference, represented by the null literal null, which is formed from ASCII characters.

A null literal is always of the null type.

Only a reference of type which is assigned to null is allocated. You don't assign any value (object) to the reference. Such allocation is specific to JVM how much reference will take and in which memory area it will be allocated.

PuTTY Connection Manager download?

Try SuperPuTTY. It is similar to puttycm.

You can also try mobaxterm or mremoteng

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

TypeError: got multiple values for argument

This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.

def color_box(color, *args, **kwargs):
    painter.select_color(color)
    painter.draw_box(*args, **kwargs)

Then the call

color_box("blellow", color="green", height=20, width=30)

will fail because two values are assigned to color: "blellow" as positional and "green" as keyword. (painter.draw_box is supposed to accept the height and width arguments).

This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:

# misplaced height and width
color_box(20, 30, color="green")

Here, color is assigned 20, then args=[30] and color is again assigned "green".

How to call a function from a string stored in a variable?

Solution: Use PHP7

Note: For a summarized version, see TL;DR at the end of the answer.

Old Methods

Update: One of the old methods explained here has been removed. Refer to other answers for explanation on other methods, it is not covered here. By the way, if this answer doesn't help you, you should return upgrading your stuff. PHP 5.6 support has ended in January 2019 (now even PHP 7.1 and 7.2 are not being supported). See supported versions for more information.

As others mentioned, in PHP5 (and also in newer versions like PHP7) we could use variables as function names, use call_user_func() and call_user_func_array() (which, personally, I hate those functions), etc.

New Methods

As of PHP7, there are new ways introduced:

Note: Everything inside <something> brackets means one or more expressions to form something, e.g. <function_name> means expressions forming a function name.

Dynamic Function Call: Function Name On-the-fly

We can use one or more expressions inside parentheses as the function name in just one go, in the form of:

(<function_name>)(arguments);

For example:

function something(): string
{
    return "something";
}

$bar = "some_thing";

(str_replace("_", "", $bar))(); // something

// Possible, too; but generally, not recommended, because makes your code more complicated
(str_replace("_", "", $bar))()(); 

Note: Although removing the parentheses around str_replace() is not an error, putting parentheses makes code more readable. However, you cannot do that sometimes, e.g. while using . operator. To be consistent, I recommend you to put the parentheses always.

Dynamic Method Call: Method Name On-the-fly

Just like dynamic function calls, we can do the same way with method calls, surrounded by curly braces instead of parentheses (for extra forms, navigate to TL;DR section):

$object->{<method_name>}(arguments);
$object::{<method_name>}(arguments);

See it in an example:

class Foo
{
    public function another(): string
    {
        return "something";
    }
}

$bar = "another thing";

(new Something())->{explode(" ", $bar)[0]}(); // something

Dynamic Method Call: The Array Syntax

A more elegant way added in PHP7 is the following:

[<object>, <method_name>](arguments);
[<class_name>, <method_name>](arguments); // Static calls only

As an example:

class Foo
{
    public function nonStaticCall()
    {
        echo "Non-static call";
    }
    public static function staticCall()
    {
        echo "Static call";
    }
}

$x = new X();

[$x, "non" . "StaticCall"](); // Non-static call
[$x, "static" . "Call"](); // Static call

Note: The benefit of using this method over the previous one is that, you don't care about the call type (i.e. whether it's static or not).

Note: If you care about performance (and micro-optimizations), don't use this method. As I tested, this method is really slower than other methods (more than 10 times).

Extra Example: Using Anonymous Classes

Making things a bit complicated, you could use a combination of anonymous classes and the features above:

$bar = "SomeThing";

echo (new class {
    public function something()
    {
        return 512;
    }
})->{strtolower($bar)}(); // 512

TL;DR (Conclusion)

Generally, in PHP7, using the following forms are all possible:

// Everything inside `<something>` brackets means one or more expressions
// to form something

// Dynamic function call
(<function_name>)(arguments)

// Dynamic method call on an object
$object->{<method_name>}(arguments)
$object::{<method_name>}(arguments)

// Dynamic method call on a dynamically-generated object
(<object>)->{<method_name>}(arguments)
(<object>)::{<method_name>}(arguments)

// Dynamic method call, statically
ClassName::{<method_name>}(arguments)
(<class_name>)::{<method_name>}(arguments)

// Dynamic method call, array-like (no different between static and non-static calls
[<object>, <method_name>](arguments)

// Dynamic method call, array-like, statically
[<class_name>, <method_name>](arguments)

Special thanks to this PHP talk.

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

final keyword in method parameters

The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all. But that's enough.

Some programmers (like me) think that's a very good thing and use final on almost every parameter. It makes it easier to understand a long or complex method (though one could argue that long and complex methods should be refactored.) It also shines a spotlight on method parameters that aren't marked with final.

How to "scan" a website (or page) for info, and bring it into my program?

Use a HTML parser like Jsoup. This has my preference above the other HTML parsers available in Java since it supports jQuery like CSS selectors. Also, its class representing a list of nodes, Elements, implements Iterable so that you can iterate over it in an enhanced for loop (so there's no need to hassle with verbose Node and NodeList like classes in the average Java DOM parser).

Here's a basic kickoff example (just put the latest Jsoup JAR file in classpath):

package com.stackoverflow.q2835505;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Test {

    public static void main(String[] args) throws Exception {
        String url = "https://stackoverflow.com/questions/2835505";
        Document document = Jsoup.connect(url).get();

        String question = document.select("#question .post-text").text();
        System.out.println("Question: " + question);

        Elements answerers = document.select("#answers .user-details a");
        for (Element answerer : answerers) {
            System.out.println("Answerer: " + answerer.text());
        }
    }

}

As you might have guessed, this prints your own question and the names of all answerers.

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

What is the difference between new/delete and malloc/free?

  • new is an operator, whereas malloc() is a fucntion.
  • new returns exact data type, while malloc() returns void * (pointer of type void).
  • malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
  • delete and free() both can be used for 'NULL' pointers.

HTTP Request in Kotlin

I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

val url = "https://example.com/endpoint"

val client = OkHttpClient()

val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
        .addHeader("Authorization", "Bearer $token")
        .url(url)
        .post(body)
        .build()

val  response = client . newCall (request).execute()

println(response.request())
println(response.body()!!.string())

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

UPDATE: January 25th, 2021 Everything is okay with the most updated versions.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.12.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

Get Method

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
            .url(url)
            .get()
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}

POST Method

fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val body = jacksonString.toRequestBody(mediaType)

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}

How to truncate string using SQL server

You could also use the below, the iif avoids the case statement and only adds ellipses when required (only good in SQL Server 2012 and later) and the case statement is more ANSI compliant (but more verbose)

SELECT 
  col, LEN(col), 
  col2, LEN(col2), 
  col3, LEN(col3) FROM (
  SELECT 
    col, 
    LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2, 
    LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3 
  from (
      select 'this is a long string. One that is longer than 15 characters' as col
      UNION 
      SELECT 'short string' AS col
      UNION 
      SELECT 'string==15 char' AS col
      UNION 
      SELECT NULL AS col
      UNION 
      SELECT '' AS col
) x
) y

Java JTable setting Column Width

Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.

TableColumn column = null;
for (int i = 0; i < 3; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 0) 
        column.setMaxWidth(10);
    if (i == 2)
        column.setMaxWidth(50);
}

Is there Unicode glyph Symbol to represent "Search"

Displayed correct at Chrome OS - screenshots from this system.

tibetan astrological sign sgra gcan -char rtags U+0F17 ? U+0F17

telephone recorder (U+2315) ? U+2315

lepcha letter gla (U+1C04) ? U+1C04

How can I remove all text after a character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

How do I get an apk file from an Android device?

No Root and no ADB tools required method. Install MyAppSharer app from the play store.

Loop through checkboxes and count each one checked or unchecked

I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.

Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.

Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.

So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.

What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.

The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.

LINQ query on a DataTable

                    //Json Formating code
                    //DT is DataTable
                    var filter = (from r1 in DT.AsEnumerable()

                                  //Grouping by multiple columns 
                                  group r1 by new
                                  {
                                      EMPID = r1.Field<string>("EMPID"),
                                      EMPNAME = r1.Field<string>("EMPNAME"),

                                  } into g
                                  //Selecting as new type
                                  select new
                                  {

                                      EMPID = g.Key.EMPID,
                                      MiddleName = g.Key.EMPNAME});

how to make a specific text on TextView BOLD

If you are using Kotlin, it becomes even easier to do by using core-ktx, as it provides a domain-specific-language (DSL) for doing this:

val string: SpannedString = buildSpannedString {
    bold {
        append("foo")
    }
    append("bar")     
}

More options provided by it are:

append("Hello There")
bold {
    append("bold")
    italic {
        append("bold and italic")
        underline {
            append("then some text with underline")
        }
    }
}

At last, you can just to:

textView.text = string

get all the images from a folder in php

Here is my some code

$dir          = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);

function Get_ImagesToFolder($dir){
    $ImagesArray = [];
    $file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];

    if (file_exists($dir) == false) {
        return ["Directory \'', $dir, '\' not found!"];
    } 
    else {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $file) {
            $file_type = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($file_type, $file_display) == true) {
                $ImagesArray[] = $file;
            }
        }
        return $ImagesArray;
    }
}

Storing database records into array

You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:

if (isset($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $sql = "SELECT * FROM users WHERE username = '$search'";
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($res);
  if ($row){
    print_r($row); //do whatever you want with found info
  }
}

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

rotate image with css

I know this topic is old, but there are no correct answers.

rotation transform rotates the element from its center, so, a wider element will rotate this way:

enter image description here

Applying overflow: hidden hides the longest dimension as you can see here:

enter image description here

_x000D_
_x000D_
img{_x000D_
  border: 1px solid #000;_x000D_
  transform:          rotate(270deg);_x000D_
  -ms-transform:      rotate(270deg);_x000D_
  -moz-transform:     rotate(270deg);_x000D_
  -webkit-transform:  rotate(270deg);_x000D_
  -o-transform:       rotate(270deg);_x000D_
}_x000D_
.imagetest{_x000D_
  overflow: hidden_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" width=100%/>_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

So, what I do is some calculations, in my example the picture is 455px width and 111px height and we have to add some margins based on these dimensions:

  • left margin: (width - height)/2
  • top margin: (height - width)/2

in CSS:

margin: calc((455px - 111px)/2) calc((111px - 455px)/2);

Result:

enter image description here

_x000D_
_x000D_
img{_x000D_
  border: 1px solid #000;_x000D_
  transform:          rotate(270deg);_x000D_
  -ms-transform:      rotate(270deg);_x000D_
  -moz-transform:     rotate(270deg);_x000D_
  -webkit-transform:  rotate(270deg);_x000D_
  -o-transform:       rotate(270deg);_x000D_
  /* 455 * 111 */_x000D_
  margin: calc((455px - 111px)/2) calc((111px - 455px)/2);_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" />_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
_x000D_
_x000D_

I hope it helps someone!

How to create a directory using Ansible

here is easier way.

- name: create dir command: mkdir -p dir dir/a dir/b

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

This compilation unit is not on the build path of a Java project

Since you imported the project as a General Project, it does not have the java nature and that is the problem.

Add the below lines in the .project file of your workspace and refresh.

<natures>
      <nature>org.eclipse.jdt.core.javanature</nature>
</natures>

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

Note that besides all other comments there is a small difference, which should be mentioned here for completeness!

With the empty catch clause you can catch non-CLSCompliant Exceptions when the assembly is marked with "RuntimeCompatibility(WrapNonExceptionThrows = false)" (which is true by default since CLR2). [1][2][3]

[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx

[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx

[3] Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?

How do I convert array of Objects into one Object in JavaScript?

Using Object.fromEntries:

_x000D_
_x000D_
const array = [_x000D_
    { key: "key1", value: "value1" },_x000D_
    { key: "key2", value: "value2" },_x000D_
];_x000D_
_x000D_
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));_x000D_
_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

Virtualenv Command Not Found

If you're using Linux, open your terminal and type virtualenv halfway and autocomplete with tab key. If there's no auto-completion install virtualenv on your system by running:

mycomp$sudo apt-get install virtualenv
//if you're already super user.
mycomp#apt-get install virtualenv

You can now navigate to where you want to create your project and do:

myprj$pip3 install virtualenv    
//to install python 3.5 and above  
myprj$virtualenv venv --python=python3.5  
//to activate virtualenv  
(venv)myprj$source venv/bin/activate  
(venv)myprj$deactivate

remove / reset inherited css from an element

One simple approach would be to use the !important modifier in css, but this can be overridden in the same way from users.

Maybe a solution can be achieved with jquery by traversing the entire DOM to find your (re)defined classes and removing / forcing css styles.

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

How can I align text directly beneath an image?

This centers the "A" below the image:

<div style="text-align:center">
  <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/opentoselect.gif" />
  <br />
  A
</div>

That is ASP.Net and it would render the HTML as:

<div style="text-align:center">
<img id="Image1" src="Images/opentoselect.gif" style="border-width:0px;" />
<br />
A
</div>

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

SQL left join vs multiple tables on FROM line?

Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.

How to dynamically create generic C# object using reflection?

Indeed you would not be able to write the last line.

But you probably don't want to create the object, just for the sake or creating it. You probably want to call some method on your newly created instance.

You'll then need something like an interface :

public interface ITask 
{
    void Process(object o);
}

public class Task<T> : ITask
{ 
   void ITask.Process(object o) 
   {
      if(o is T) // Just to be sure, and maybe throw an exception
        Process(o as T);
   }

   public void Process(T o) { }
}

and call it with :

Type d1 = Type.GetType("TaskA"); //or "TaskB"
Type[] typeArgs = { typeof(Item) };
Type makeme = d1.MakeGenericType(typeArgs);
ITask task = Activator.CreateInstance(makeme) as ITask;

// This can be Item, or any type derived from Item
task.Process(new Item());

In any case, you won't be statically cast to a type you don't know beforehand ("makeme" in this case). ITask allows you to get to your target type.

If this is not what you want, you'll probably need to be a bit more specific in what you are trying to achieve with this.

Setting background color for a JFrame

public nameOfTheClass()  {

final Container c = this.getContentPane();

  public void actionPerformed(ActionEvent e) {
    c.setBackground(Color.white); 
  }
}

Detect Scroll Up & Scroll down in ListView

Store the firstVisibleItem and on the next onScroll check if the new firstVisibleItem is smaller or greater than the previous one.

Example pseudocode (not tested):

int lastVisibleItem = 0;
boolean isScrollingDown = false;

void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if (firstVisibleItem > lastVisibleItem) {
        isScrollingDown = true;
    }
    else {
        isScrollingDown = false;
    }
    lastVisibleItem = firstVisibleItem;
}

Sum up a column from a specific row down

This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:

=sum(c6:c1048576)

For more robust solutions, see the other answers.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How do you unit test private methods?

I've also used the InternalsVisibleToAttribute method. It's worth mentioning too that, if you feel uncomfortable making your previously private methods internal in order to achieve this, then maybe they should not be the subject of direct unit tests anyway.

After all, you're testing the behaviour of your class, rather than it's specific implementation - you can change the latter without changing the former and your tests should still pass.

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

pandas: How do I split text in a column into multiple rows?

This seems a far easier method than those suggested elsewhere in this thread.

split rows in pandas dataframe

Create or write/append in text file

Try something like this:

 $txt = "user id date";
 $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

How to prevent colliders from passing through each other?

1.) Never use MESH COLLIDER. Use combination of box and capsule collider.

2.) Check constraints in RigidBody. If you tick Freeze Position X than it will pass through the object on the X axis. (Same for y axis).

Ring Buffer in Java

Use a Queue

Queue<String> qe=new LinkedList<String>();

qe.add("a");
qe.add("b");
qe.add("c");
qe.add("d");

System.out.println(qe.poll()); //returns a
System.out.println(qe.poll()); //returns b
System.out.println(qe.poll()); //returns c
System.out.println(qe.poll()); //returns d

There's five simple methods of a Queue

  • element() -- Retrieves, but does not remove, the head of this queue.

  • offer(E o) -- Inserts the specified element into this queue, if
    possible.

  • peek() -- Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.

  • poll() -- Retrieves and removes the head of this queue, or null if this queue is empty.

  • remove() -- Retrieves and removes the head of this queue.

How do I speed up the gwt compiler?

If you run the GWT compiler with the -localWorkers flag, the compiler will compile multiple permutations in parallel. This lets you use all the cores of a multi-core machine, for example -localWorkers 2 will tell the compiler to do compile two permutations in parallel. You won't get order of magnitudes differences (not everything in the compiler is parallelizable) but it is still a noticable speedup if you are compiling multiple permutations.

If you're willing to use the trunk version of GWT, you'll be able to use hosted mode for any browser (out of process hosted mode), which alleviates most of the current issues with hosted mode. That seems to be where the GWT is going - always develop with hosted mode, since compiles aren't likely to get magnitudes faster.

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

Mean Squared Error in Numpy?

Just for kicks

mse = (np.linalg.norm(A-B)**2)/len(A)

How can I clear the NuGet package cache using the command line?

Clearing the cache

With dotnet core cli

dotnet nuget locals all --clear

With Visual Studio 2017

  1. Go to menu Tools ? NuGet Package Manager ? Package Manager Settings.
  2. Click Clear All NuGet Cache(s):

visual studio NuGet Package Manager General settings screenshot

With the nuget cli

Download and install the NuGet command line tool.

nuget locals all -clear

With windows command line

del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q

(can be used in a .bat file)

With PowerShell

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg

Or 'quiet' mode (without error messages):

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null

Cache location

Windows

%userprofile%\.nuget\packages

Linux

~/.nuget/

Build server

%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache

Example:

C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache

This answer is a rollup of all the existing answers for your convenience

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

The standard Servlet API doesn't support this facility. You may want either to use a rewrite-URL filter for this like Tuckey's one (which is much similar Apache HTTPD's mod_rewrite), or to add a check in the doFilter() method of the Filter listening on /*.

String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
    chain.doFilter(request, response); // Just continue chain.
} else {
    // Do your business stuff here for all paths other than /specialpath.
}

You can if necessary specify the paths-to-be-ignored as an init-param of the filter so that you can control it in the web.xml anyway. You can get it in the filter as follows:

private String pathToBeIgnored;

public void init(FilterConfig config) {
    pathToBeIgnored = config.getInitParameter("pathToBeIgnored");
}

If the filter is part of 3rd party API and thus you can't modify it, then map it on a more specific url-pattern, e.g. /otherfilterpath/* and create a new filter on /* which forwards to the path matching the 3rd party filter.

String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
    chain.doFilter(request, response); // Just continue chain.
} else {
    request.getRequestDispatcher("/otherfilterpath" + path).forward(request, response);
}

To avoid that this filter will call itself in an infinite loop you need to let it listen (dispatch) on REQUEST only and the 3rd party filter on FORWARD only.

See also:

Splitting a continuous variable into equal sized groups

If you want to split into 3 equally distributed groups, the answer is the same as Ben Bolker's answer above - use ggplot2::cut_number(). For sake of completion here are the 3 methods of converting continuous to categorical (binning).

  • cut_number(): Makes n groups with (approximately) equal numbers of observation
  • cut_interval(): Makes n groups with equal range
  • cut_width(): Makes groups of width

My go-to is cut_number() because this uses evenly spaced quantiles for binning observations. Here's an example with skewed data.

library(tidyverse)

skewed_tbl <- tibble(
    counts = c(1:100, 1:50, 1:20, rep(1:10, 3), 
               rep(1:5, 5), rep(1:2, 10), rep(1, 20))
    ) %>%
    mutate(
        counts_cut_number   = cut_number(counts, n = 4),
        counts_cut_interval = cut_interval(counts, n = 4),
        counts_cut_width    = cut_width(counts, width = 25)
        ) 

# Data
skewed_tbl
#> # A tibble: 265 x 4
#>    counts counts_cut_number counts_cut_interval counts_cut_width
#>     <dbl> <fct>             <fct>               <fct>           
#>  1      1 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  2      2 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  3      3 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  4      4 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  5      5 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  6      6 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  7      7 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  8      8 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  9      9 (3,13]            [1,25.8]            [-12.5,12.5]    
#> 10     10 (3,13]            [1,25.8]            [-12.5,12.5]    
#> # ... with 255 more rows

summary(skewed_tbl$counts)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>    1.00    3.00   13.00   25.75   42.00  100.00

# Histogram showing skew
skewed_tbl %>%
    ggplot(aes(counts)) +
    geom_histogram(bins = 30)

# cut_number() evenly distributes observations into bins by quantile
skewed_tbl %>%
    ggplot(aes(counts_cut_number)) +
    geom_bar()

# cut_interval() evenly splits the interval across the range
skewed_tbl %>%
    ggplot(aes(counts_cut_interval)) +
    geom_bar()

# cut_width() uses the width = 25 to create bins that are 25 in width
skewed_tbl %>%
    ggplot(aes(counts_cut_width)) +
    geom_bar()

Created on 2018-11-01 by the reprex package (v0.2.1)

How to make inline plots in Jupyter Notebook larger?

A quick fix to "plot overlap" is to use plt.tight_layout():

Example (in my case)

for i,var in enumerate(categorical_variables):
    plt.title(var)
    plt.xticks(rotation=45)
    df[var].hist()
    plt.subplot(len(categorical_variables)/2, 2, i+1)

plt.tight_layout()

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

ImportError: No module named site on Windows

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5. I renamed it to C:\Python27\ and it resolved the problem.

Returning a boolean from a Bash function

Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:

foo()
{
    if [ "$1" == "bar" ]; then
        true; return
    else
        false; return
    fi;
}

That eliminates the ugly two line requirement for every return statement.

Using comma as list separator with AngularJS

You can use CSS to fix it too

<div class="some-container">
[ <span ng-repeat="something in somethings">{{something}}<span class="list-comma">, </span></span> ]
</div>

.some-container span:last-child .list-comma{
    display: none;
}

But Andy Joslin's answer is best

Edit: I changed my mind I had to do this recently and I ended up going with a join filter.

How to check if a query string value is present via JavaScript?

Using URL:

url = new URL(window.location.href);

if (url.searchParams.get('test')) {

}

EDIT: if you're sad about compatibility, I'd highly suggest https://github.com/medialize/URI.js/.

Concatenate two slices in Go

I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.

c := append(a, b...)

This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.

To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:

"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."

append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.

Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.

la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)

la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

MySQL Error 1264: out of range value for column

tl;dr

Make sure your AUTO_INCREMENT is not out of range. In that case, set a new value for it with:

ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number

Explanation

AUTO_INCREMENT can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.

Solution

If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT to one bigger than the latest row's id. So if your latest row's id is 100 then:

ALTER TABLE table_name AUTO_INCREMENT=101

If you would like to check AUTO_INCREMENT's current value, use this command:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

Why should Java 8's Optional not be used in arguments

Check out the JavaDoc in JDK10, https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html, an API note is added:

API Note: Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors.

Intellij IDEA Java classes not auto compiling on save

I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.

In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Pass Hidden parameters using response.sendRedirect()

To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.

String value="xyz";

response.sendRedirect("/content/test.jsp?var="+value);

What is the best (idiomatic) way to check the type of a Python variable?

That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

{type(str()): do_something_with_a_string,
 type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()

A bit more concise and pythonic wouldn't you say?


Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

{str: do_something_with_a_string,
 dict: do_something_with_a_dict}.get(type(x), errorhandler)()

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this question is already been answered but for new comers those two solutions may help:

  1. Make sure your gmail is allowing low secure apps to sign in, you can turn it on here: https://www.google.com/settings/security/lesssecureapps.
  2. Change your password.

Remove empty elements from an array in Javascript

This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)

/* appjet:version 0.1 */
function Joes_remove(someArray) {
    var newArray = [];
    var element;
    for( element in someArray){
        if(someArray[element]!=undefined ) {
            newArray.push(someArray[element]);
        }
    }
    return newArray;
}

var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/

SQL Server: Examples of PIVOTing String data

Well, for your sample and any with a limited number of unique columns, this should do it.

select 
    distinct a,
    (select distinct t2.b  from t t2  where t1.a=t2.a and t2.b='VIEW'),
    (select distinct t2.b from t t2  where t1.a=t2.a and t2.b='EDIT')
from t t1

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

ImportError: No module named - Python

from ..gen_py.lib import MyService

or

from main.gen_py.lib import MyService

Make sure you have a (at least empty) __init__.py file on each directory.

UTF-8 encoded html pages show ? (questions marks) instead of characters

The problem is the charset that is being used by apache to serve the pages. I work with Linux, so I don't know anything about XAMPP. I had the same problem too, what I did to solve the problem was to add the charset to the charset config file (It is commented by default).

In my case I have it in /etc/apache2/conf.d/charset but, since you're using Windows the location is different. So I'm giving you this like an idea of how to solve it.

At the end, my charset config file is like this:

# Read the documentation before enabling AddDefaultCharset.
# In general, it is only a good idea if you know that all your files
# have this encoding. It will override any encoding given in the files
# in meta http-equiv or xml encoding tags.

AddDefaultCharset UTF-8

I hope it helps.

Tooltips with Twitter Bootstrap

Simple use of this:

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip">
   tooltip
</a>

Using jQuery:

$(document).ready(function(){
    $('#mytooltip').tooltip();
});

You can left side of tooltip u can simple add this->data-placement="left"

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip" data-placement="left">tooltip</a>

Using CMake to generate Visual Studio C++ project files

Lots of great answers here but they might be superseded by this CMake support in Visual Studio (Oct 5 2016)

Make div scrollable

use css overflow:scroll; property. you need to specify height and width then you will be able to scroll horizontally and vertically or either one of two scroll by setting overflow-x:auto; or overflow-y:auto;

ERROR: Google Maps API error: MissingKeyMapError

Update django-geoposition at least to version 0.2.3 and add this to settings.py:

GEOPOSITION_GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Python object deleting itself

In this specific context, your example doesn't make a lot of sense.

When a Being picks up an Item, the item retains an individual existence. It doesn't disappear because it's been picked up. It still exists, but it's (a) in the same location as the Being, and (b) no longer eligible to be picked up. While it's had a state change, it still exists.

There is a two-way association between Being and Item. The Being has the Item in a collection. The Item is associated with a Being.

When an Item is picked up by a Being, two things have to happen.

  • The Being how adds the Item in some set of items. Your bag attribute, for example, could be such a set. [A list is a poor choice -- does order matter in the bag?]

  • The Item's location changes from where it used to be to the Being's location. There are probably two classes os Items - those with an independent sense of location (because they move around by themselves) and items that have to delegate location to the Being or Place where they're sitting.

Under no circumstances does any Python object ever need to get deleted. If an item is "destroyed", then it's not in a Being's bag. It's not in a location.

player.bag.remove(cat)

Is all that's required to let the cat out of the bag. Since the cat is not used anywhere else, it will both exist as "used" memory and not exist because nothing in your program can access it. It will quietly vanish from memory when some quantum event occurs and memory references are garbage collected.

On the other hand,

here.add( cat )
player.bag.remove(cat)

Will put the cat in the current location. The cat continues to exist, and will not be put out with the garbage.

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

How to change port for jenkins window service when 8080 is being used

On Windows (with Windows Service).

Edit the file C:\Program Files (x86)\Jenkins\jenkins.xml with 8083 if you want 8083 port.

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>

Increment a database field by 1

If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:

INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;

If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

Install NuGet via PowerShell script

Without having Visual Studio, you can grab Nuget from: http://nuget.org/nuget.exe

For command-line executions using this, check out: http://docs.nuget.org/docs/reference/command-line-reference

With respect to Powershell, just copy the nuget.exe to the machine. No installation required, just execute it using commands from the above documentation.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

The following will do.

string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

Canvas width and height in HTML5

The canvas DOM element has .height and .width properties that correspond to the height="…" and width="…" attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;

Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height); to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.

Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height and style.width CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width  = 400;
canvas.height = 300; 
canvas.style.width  = '800px';
canvas.style.height = '600px';

See this live example of a canvas that is zoomed in by 4x.

_x000D_
_x000D_
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth   = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle   = '#eff';_x000D_
_x000D_
ctx.fillRect(  10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect(   40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect(   70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
_x000D_
_x000D_

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

std::string formatting like sprintf

I usually use this:

std::string myformat(const char *const fmt, ...)
{
        char *buffer = NULL;
        va_list ap;

        va_start(ap, fmt);
        (void)vasprintf(&buffer, fmt, ap);
        va_end(ap);

        std::string result = buffer;
        free(buffer);

        return result;
}

Disadvantage: not all systems support vasprint

Why use pointers?

  • Why use pointers over normal variables?

Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...

  • When and where should I use pointers?

Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.

  • How do you use pointers with arrays?

With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are very similar (but not the same - e.g., sizeof will return different values):

char* a = "Hello";
char a[] = "Hello";

You can reach any element in the array like this

printf("Second char is: %c", a[1]);

Index 1 since the array starts with element 0. :-)

Or you could equally do this

printf("Second char is: %c", *(a+1));

The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:

printf("Second char is: %s", (a+1)); /* WRONG */

But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?

char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);

This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).

Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:

char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);

Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

Concat a string to SELECT * MySql

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

How to check if a string array contains one string in JavaScript?

This will do it for you:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle)
            return true;
    }
    return false;
}

I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

What is the difference between printf() and puts() in C?

puts is the simple choice and adds a new line in the end and printfwrites the output from a formatted string.

See the documentation for puts and for printf.

I would recommend to use only printf as this is more consistent than switching method, i.e if you are debbugging it is less painfull to search all printfs than puts and printf. Most times you want to output a variable in your printouts as well, so puts is mostly used in example code.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

You can do this:

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).

I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.

In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.

How to convert image to byte array

You can use File.ReadAllBytes() method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes() method.

Hope this helps.

You can find more information and sample code here.

How to detect the character encoding of a text file?

If your file starts with the bytes 60, 118, 56, 46 and 49, then you have an ambiguous case. It could be UTF-8 (without BOM) or any of the single byte encodings like ASCII, ANSI, ISO-8859-1 etc.

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

Error message "Linter pylint is not installed"

If you're using pipenv then you just have to

pipenv install pylint

to install Pylint to your virtual environment

pipenv shell

to activate the environment and thus make Pylint available. Then start code in that environment

code .

Boom! you're good to code ;-)

ExecuteReader: Connection property has not been initialized

After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... Add

cmd.Connection = conn;

Hope this help

Python "SyntaxError: Non-ASCII character '\xe2' in file"

After about a half hour of looking through stack overflow, It dawned on me that if the use of a single quote " ' " in a comment will through the error:

SyntaxError: Non-ASCII character '\xe2' in file

After looking at the traceback i was able to locate the single quote used in my comment.

ASP.Net 2012 Unobtrusive Validation with jQuery

Other than the required "jquery" ScriptResourceDefinition in Global.asax (use your own paths):

    protected void Application_Start(object sender, EventArgs e)
    {            
        ScriptManager.ScriptResourceMapping.AddDefinition(
            "jquery",
            new ScriptResourceDefinition
            {
                Path = "/static/scripts/jquery-1.8.3.min.js",
                DebugPath = "/static/scripts/jquery-1.8.3.js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "jQuery"
            });
    }

You additionally only need to explicitly add "WebUIValidation.js" after "jquery" ScriptReference in ScriptManager (the most important part):

       <asp:ScriptManager runat="server" EnableScriptGlobalization="True" EnableCdn="True">
            <Scripts>
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" />
            </Scripts>
        </asp:ScriptManager>

If you add it before "jquery", or if you don't add any or both of them at all (ASP.Net will then automatically add it before "jquery") - the client validation will be completely broken:

http://connect.microsoft.com/VisualStudio/feedback/details/748064/unobtrusive-validation-breaks-with-a-script-manager-on-the-page

You don't need any of those NuGet packages at all, nor any additional ScriptReference (some of which are just duplicates, or even a completely unnecessary bloat - as they are added automatically by ASP.Net if needed) mentioned in your blog.

EDIT: you don't need to explicitly add "WebForms.js" as well (removed it from the example) - and if you do, its LoadSuccessExpression will be ignored for some reason

Are there pointers in php?

entryId is an instance property of the current class ($this) And $entryId is a local variable

Android: Quit application when press back button

In order to exit from the app on pressing back button you have to first clear all the top activities and then start the ACTION_MAIN of android phone

So, you have to write all these code only which is mentioned below :

Note : In your case MainActivity get replaced by YourActivity

@Override
public void onBackPressed() {

        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.super.onBackPressed();
                        quit();
                    }
                }).create().show();
    }


public void quit() {
        Intent start = new Intent(Intent.ACTION_MAIN);
        start.addCategory(Intent.CATEGORY_HOME);
        start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        start.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(start);
    }

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

How to connect to MySQL Database?

Install Oracle's MySql.Data NuGet package.

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

Example:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

Convert and format a Date in JSP

In JSP, you'd normally like to use JSTL <fmt:formatDate> for this. You can of course also throw in a scriptlet with SimpleDateFormat, but scriptlets are strongly discouraged since 2003.

Assuming that ${bean.date} returns java.util.Date, here's how you can use it:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />

If you're actually using a java.util.Calendar, then you can invoke its getTime() method to get a java.util.Date out of it that <fmt:formatDate> accepts:

<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />

Or, if you're actually holding the date in a java.lang.String (this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date instead of as java.lang.String!), here's how you can convert from one date string format e.g. MM/dd/yyyy to another date string format e.g. yyyy-MM-dd with help of JSTL <fmt:parseDate>.

<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

How to create a custom-shaped bitmap marker with Android map API v2

In the Google Maps API v2 Demo there is a MarkerDemoActivity class in which you can see how a custom Image is set to a GoogleMap.

// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
    .position(SYDNEY)
    .title("Sydney")
    .snippet("Population: 4,627,300")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));

As this just replaces the marker with an image you might want to use a Canvas to draw more complex and fancier stuff:

Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas1 = new Canvas(bmp);

// paint defines the text color, stroke width and size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);

// modify canvas
canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(),
    R.drawable.user_picture_image), 0,0, color);
canvas1.drawText("User Name!", 30, 40, color);

// add marker to Map
mMap.addMarker(new MarkerOptions()
    .position(USER_POSITION)
    .icon(BitmapDescriptorFactory.fromBitmap(bmp))
    // Specifies the anchor to be at a particular point in the marker image.
    .anchor(0.5f, 1));

This draws the Canvas canvas1 onto the GoogleMap mMap. The code should (mostly) speak for itself, there are many tutorials out there how to draw a Canvas. You can start by looking at the Canvas and Drawables from the Android Developer page.

Now you also want to download a picture from an URL.

URL url = new URL(user_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
conn.setDoInput(true);   
conn.connect();     
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is); 

You must download the image from an background thread (you could use AsyncTask or Volley or RxJava for that).

After that you can replace the BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image) with your downloaded image bmImg.

Ruby capitalize every word first letter

In Rails:

"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'

w/o Rails:

"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")

#OBJECT IT OUT
def titleize(str)
  str.split(/ |\_/).map(&:capitalize).join(" ")
end

#OR MONKEY PATCH IT
class String  
  def titleize
    self.split(/ |\_/).map(&:capitalize).join(" ")
  end
end

w/o Rails (load rails's ActiveSupport to patch #titleize method to String)

require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"

(some) string use cases handled by #titleize

  • "kirk douglas"
  • "kirk_douglas"
  • "kirk-douglas"
  • "kirkDouglas"
  • "KirkDouglas"

#titleize gotchas

Rails's titleize will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:

"hEy lOok".titleize #=> "H Ey Lo Ok"

because it is meant to handle camel-cased code like:

"kirkDouglas".titleize #=> "Kirk Douglas"

To deal with this edge case you could clean your string with #downcase first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:

"kirkDouglas".downcase.titleize #=> "Kirkdouglas"

How to get WordPress post featured image URL

Simply inside the loop write <?php the_post_thumbnail_url(); ?> as shown below:-

$args=array('post_type' => 'your_custom_post_type_slug','order' => 'DESC','posts_per_page'=> -1) ;
$the_qyery= new WP_Query($args);

if ($the_qyery->have_posts()) :
    while ( $the_qyery->have_posts() ) : $the_qyery->the_post();?>

<div class="col col_4_of_12">
    <div class="article_standard_view">
        <article class="item">
            <div class="item_header">
                <a href="<?php the_permalink(); ?>"><img src="<?php the_post_thumbnail_url(); ?>" alt="Post"></a>
            </div>

        </article>
    </div>
</div>            
<?php endwhile; endif; ?>

Undo a Git merge that hasn't been pushed yet

Strategy: Create a new branch from where everything was good.

Rationale: Reverting a merge is hard. There are too many solutions, depending on many factors such as whether you've committed or pushed your merge or if there were new commits since your merge. Also you still need to have a relatively deep understanding of git to adapt these solutions to your case. If you blindly follow some instructions, you can end up with an "empty merge" where nothing will be merged, and further merge attempts will make Git tell you "Already up to date".

Solution:

Let's say you want to merge dev into feature-1.

  1. Find the revision that you want to receive the merge:

    git log --oneline feature-1
    a1b2c3d4 Merge branch 'dev' into 'feature-1' <-- the merge you want to undo
    e5f6g7h8 Fix NPE in the Zero Point Module <-- the one before the merge, you probably want this one
    
  2. Check it out (go back in time):

    git checkout e5f6g7h8
    
  3. Create a new branch from there and check it out:

    git checkout -b feature-1
    

Now you can restart your merge:

  1. Merge: git merge dev

  2. Fix your merge conflicts.

  3. Commit: git commit

  4. When you're satisfied with the results, delete the old branch: git branch --delete feature-1

how to use javascript Object.defineProperty

defineProperty is a method on Object which allow you to configure the properties to meet some criterias. Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
employee.toString=function () {
    return this.firstName + " " + this.lastName;
};
console.log(employee.toString());

You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: true,
    enumerable: true,
    configurable: true
});
console.log(employee.toString());

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.

writable

One of the very annoying part of the javascript is , if you change the toString property to something else for example

enter image description here

if you run this again , everything gets breaks. Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.

enumerable

if you print all the keys inside the object , you can see all the properties including toString.

console.log(Object.keys(employee));

enter image description here

if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName

configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: false,
    enumerable: false,
    configurable: true
});

//change enumerable to false
Object.defineProperty(employee, 'toString', {

    enumerable: true
});
employee.toString="changed";
console.log(Object.keys(employee));

enter image description here

you can restrict this behavior by set configurable to false.

Orginal reference of this information is from my personal Blog

Quick way to list all files in Amazon S3 bucket?

After zach I would also recommend boto, but I needed to make a slight difference to his code:

conn = boto.connect_s3('access-key', 'secret'key')
bucket = conn.lookup('bucket-name')
for key in bucket:
    print key.name

Javascript use variable as object name

var micro=[{'test':'hello'}];

var device = 'test';

console.log(micro[device]);

Warning: A non-numeric value encountered

Check if you're not incrementing with some variable that its value is an empty string like ''.

Example:

$total = '';
$integers = range(1, 5);

foreach($integers as $integer) {
    $total += $integer;
}

How can I remount my Android/system as read-write in a bash script using adb?

Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Just do select date(timestamp_column) and you would get the only the date part. Sometimes doing select timestamp_column::date may return date 00:00:00 where it doesn't remove the 00:00:00 part. But I have seen date(timestamp_column) to work perfectly in all the cases. Hope this helps.

Converting NSData to NSString in Objective c

Objective C:

[[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

Swift:

let str = String(data: data, encoding: .ascii)

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

How to check if an integer is in a given range?

    val = val < MIN ? MIN : ( val > MAX ? MAX : val);

What's the difference between ISO 8601 and RFC 3339 Date Formats?

Is one just an extension?

Pretty much, yes - RFC 3339 is listed as a profile of ISO 8601. Most notably RFC 3339 specifies a complete representation of date and time (only fractional seconds are optional). The RFC also has some small, subtle differences. For example truncated representations of years with only two digits are not allowed -- RFC 3339 requires 4-digit years, and the RFC only allows a period character to be used as the decimal point for fractional seconds. The RFC also allows the "T" to be replaced by a space (or other character), while the standard only allows it to be omitted (and only when there is agreement between all parties using the representation).

I wouldn't worry too much about the differences between the two, but on the off-chance your use case runs in to them, it'd be worth your while taking a glance at:

How to disable Home and other system buttons in Android?

You can use Android-HomeKey-Locker to disable HOME KEY and other system keys(such as BACK KEY and MENU KEY)

Hope this will help you in your application. Thanks.

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Its a good to remember that config files can be split across secondary files to make config changes easier on different servers (dev/demo/production etc), without having to recompile code/app etc. For example we use them to allow onsite engineers to make endpoint changes without actually touching the 'real' files.

First step is to move the bindings section out of the WPF App.Config into it's own separate file.

The behaviours section is set to allow both http and https (doesn't seem to have an affect on the app if both are allowed)

<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />

And we move the bindings section out to its own file;

 <bindings configSource="Bindings.config" /> 

In the bindings.config file we switch the security based on protocol

  <!-- None = http:// -->
  <!-- Transport = https:// -->
  <security mode="None" >

Now the on site engineers only need to change the Bindings.Config file and the Client.Config where we store the actual URL for each endpoint.

This way we can change the endpoint from http to https and back again to test the app without having to change any code.

Hope this helps.

Finding three elements in an array whose sum is closest to a given number

How about something like this, which is O(n^2)

for(each ele in the sorted array)
{
    ele = arr[i] - YOUR_NUMBER;
    let front be the pointer to the front of the array;
    let rear be the pointer to the rear element of the array.;

    // till front is not greater than rear.                    
    while(front <= rear)
    {
        if(*front + *rear == ele)
        {
            print "Found triplet "<<*front<<","<<*rear<<","<<ele<<endl;
            break;
        }
        else
        {
            // sum is > ele, so we need to decrease the sum by decrementing rear pointer.
            if((*front + *rear) > ele)
                decrement rear pointer.
            // sum is < ele, so we need to increase the sum by incrementing the front pointer.
            else
                increment front pointer.
        }
    }

This finds if sum of 3 elements is exactly equal to your number. If you want closest, you can modify it to remember the smallest delta(difference between your number of current triplet) and at the end print the triplet corresponding to smallest delta.

How can we generate getters and setters in Visual Studio?

I don't have Visual Studio installed on my machine anymore (and I'm using Linux), but I do remember that there was an wizard hidden somewhere inside one of the menus that gave access to a class builder.

With this wizard, you could define all your classes' details, including methods and attributes. If I remember well, there was an option through which you could ask Visual Studio to create the setters and getters automatically for you.

I know it's quite vague, but check it out and you might find it.

Linq Syntax - Selecting multiple columns

As the other answers have indicated, you need to use an anonymous type.

As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
    .Select(x => new { x.EMAIL, x.ID });

AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.

UPDATE

If you want the entire object, then you just have to omit the call to Select(), i.e.

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);

Adding new files to a subversion repository

Normally svn add * works. But if you get message like svn: warning: W150002: due to mix off versioned and non-versioned files in working copy. Use this command:

svn add <path to directory> --force

or

svn add * --force

How to insert spaces/tabs in text using HTML/CSS

You can use &nbsp; for spaces, &lt; for < (less than, entity number &#60;) and &gt; for > (greater than, entity number &#62;).

A complete list can be found at HTML Entities.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

HTTP_HOST is the target host sent by the client. It can be manipulated freely by the user. It's no problem to send a request to your site asking for a HTTP_HOST value of www.stackoverflow.com.

SERVER_NAME comes from the server's VirtualHost definition and is therefore considered more reliable. It can, however, also be manipulated from outside under certain conditions related to how your web server is set up: See this This SO question that deals with the security aspects of both variations.

You shouldn't rely on either to be safe. That said, what to use really depends on what you want to do. If you want to determine which domain your script is running on, you can safely use HTTP_HOST as long as invalid values coming from a malicious user can't break anything.

What is a lambda expression in C++11?

What is a lambda function?

The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++ a lambda function is defined like this

[]() { } // barebone lambda

or in all its glory

[]() mutable -> T { } // T is the return type, still lacking throw()

[] is the capture list, () the argument list and {} the function body.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

The argument list

The argument list is the same as in any other C++ function.

The function body

The code that will be executed when the lambda is actually called.

Return type deduction

If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement).

Mutable

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

C++14

In C++14 lambdas have been extended by various proposals.

Initialized Lambda Captures

An element of the capture list can now be initialized with =. This allows renaming of variables and to capture by moving. An example taken from the standard:

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

and one taken from Wikipedia showing how to capture with std::move:

auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};

Generic Lambdas

Lambdas can now be generic (auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope):

auto lambda = [](auto x, auto y) {return x + y;};

Improved Return Type Deduction

C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas.

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

what is the use of Eval() in asp.net

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

<asp:TemplateField>
<ItemTemplate>
        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
        </asp:Label>
</ItemTemplate>
</asp:TemplateField>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command.it is working for me.

if "$(OutDir)"=="bin\Debug\"  goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit

Initializing a dictionary in python with a key value and no corresponding values

q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

Referencing Row Number in R

Simply:

data$rownumber = 1:nrow(Data)

How to create an empty file at the command line in Windows?

First create your file so that it exists:

echo . > myfile.txt

Then overwrite the created file with an empty version using the copy command:

copy /y nul myfile.txt

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

Each one is a different type execution.

  • ExecuteScalar is going to be the type of query which will be returning a single value.

    An example would be returning a generated id after inserting.

    INSERT INTO my_profile (Address) VALUES ('123 Fake St.'); SELECT CAST(scope_identity() AS int)

  • ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time.

    An example would be pulling profile information for one or more users.

    SELECT * FROM my_profile WHERE id = '123456'

  • ExecuteNonQuery is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something.

    An example would be updating a user's profile in the database.

    UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'

Inconsistent accessibility: property type is less accessible

make your class public access modifier,

just add public keyword infront of your class name

 namespace Test
{
  public  class Delivery
    {
        private string name;
        private string address;
        private DateTime arrivalTime;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public DateTime ArrivlaTime
        {
            get { return arrivalTime; }
            set { arrivalTime = value; }
        }

        public string ToString()
        {
            { return name + address + arrivalTime.ToString(); }
        }
    }
}

Free easy way to draw graphs and charts in C++?

My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.

How do I do redo (i.e. "undo undo") in Vim?

Use :earlier/:later. To redo everything you just need to do

later 9999999d

(assuming that you first edited the file at most 9999999 days ago), or, if you remember the difference between current undo state and needed one, use Nh, Nm or Ns for hours, minutes and seconds respectively. + :later N<CR> <=> Ng+ and :later Nf for file writes.

Finding the Eclipse Version Number

if you want to access this programatically, you can do it by figuring out the version of eclipse\plugins\org.eclipse.platform_ plugin

    String platformFile = <the above file>; //actually directory

versionPattern = Pattern.compile("\\d\\.\\d\\.\\d");
Matcher m = versionPattern.matcher(platformFile);
return m.group();

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help.

img.save("tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

What is difference between functional and imperative programming languages?

There seem to be many opinions about what functional programs and what imperative programs are.

I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.

In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.

Imperative: Shipping the computer around

Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.

Functional: Shipping recipes around

The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.

This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.

When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.

// helper function, to illustrate the point
function unwrap(val) {
  while (typeof val === "function") val = val();
  return val;
}

function inc(val) {
  return function() { unwrap(val) + 1 };
}

function dec(val) {
  return function() { unwrap(val) - 1 };
}

function add(val1, val2) {
  return function() { unwrap(val1) + unwrap(val2) }
}

// lets "calculate" something

let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))

// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13

// lets compose a new function

let doubler = function(val) {
  return add(val, val);
}

// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)

// another function
let doublerMinusOne = (val) => dec(add(val, val));

// Will this be calculating anything?

let twentyFive = doubler(thirteen)

// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26

The unwrap function will evaluate all the functions to the point of having a scalar value.

Language Design Consequences

Some nice features in imperative languages, are impossible in functional languages. For example the value++ expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.

On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.

Functional languages have great difficulty with unary operators like for example ++ to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".

Implementing a unary operator would have to be implemented something like this:

let value = 10;

function increment_operator(value) {
  return function() {
    unwrap(value) + 1;
  }
}

value++ // would "under the hood" become value = increment_operator(value)

Note that the unwrap function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.

It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.

The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.

Under the hood, it boils down to two different approaches to come up with an output when provided with an input.

Below, I'll try to make an illustration of a city with the following items:

  1. The Computer
  2. Your Home
  3. The Fibonaccis

Imperative Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Put The Computer into a box and mark it with a sticky note:

    Field Value
    Mail Address The Fibonaccis
    Return Address Your Home
    Parameters 3
    Return Value undefined

    and send off the computer.

  2. The Fibonaccis will upon receiving the box do as they always do:

    • Is the parameter < 2?

      • Yes: Change the sticky note, and return the computer to the post office:

        Field Value
        Mail Address The Fibonaccis
        Return Address Your Home
        Parameters 3
        Return Value 0 or 1 (returning the parameter)

        and return to sender.

      • Otherwise:

        1. Put a new sticky note on top of the old one:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, step 2, c/oThe Fibonaccis
          Parameters 2 (passing parameter-1)
          Return Value undefined

          and send it.

        2. Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, done, c/o The Fibonaccis
          Parameters 2 (passing parameter-2)
          Return Value undefined
        3. By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.

          Field Value
          Mail Address The Fibonaccis
          Return Address Your Home
          Parameters 3
          Return Value 2 (returnValue1 + returnValue2)

          and return to sender.

As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.

The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.

Functional Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Write the following down on a sticky note:

    Field Value
    Instructions The Fibonaccis
    Parameters 3

That's essentially it. That sticky note now represents the computation result of fib(3).

We have attached the parameter 3 to the recipe named The Fibonaccis. The computer does not have to perform any calculations, unless somebody needs the scalar value.

Functional Javascript Example

I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.

fib: (n) => if (                         
  n < 2               // test
  n                   // when true
  fib(n-1) + fib(n-2) // when false
)
print(fib(4));

This code can be compiled both into imperative and functional "bytecode".

The imperative javascript version would be:

let fib = (n) => 
  n < 2 ?
  n : 
  fib(n-1) + fib(n-2);

The HALF functional javascript version would be:

let fib = (n) => () =>
  n < 2 ?
  n :
  fib(n-1) + fib(n-2);

The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.

let unwrap = ($) =>
  typeof $ !== "function" ? $ : unwrap($());

let $if = ($test, $whenTrue, $whenFalse) => () =>
  unwrap($test) ? $whenTrue : $whenFalse;

let $lessThen = (a, b) => () =>
  unwrap(a) < unwrap(b);

let $add = ($value, $amount) => () =>
  unwrap($value) + unwrap($amount);

let $sub = ($value, $amount) => () =>
  unwrap($value) - unwrap($amount);

let $fib = ($n) => () =>
  $if(
    $lessThen($n, 2),
    $n,
    $add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
  );

I'll manually "compile" it into javascript code:

"use strict";

// Library of functions:
  /**
   * Function that resolves the output of a function.
   */
  let $$ = (val) => {
    while (typeof val === "function") {
      val = val();
    }
    return val;
  }

  /**
   * Functional if
   *
   * The $ suffix is a convention I use to show that it is "functional"
   * style, and I need to use $$() to "unwrap" the value when I need it.
   */
  let if$ = (test, whenTrue, otherwise) => () =>
    $$(test) ? whenTrue : otherwise;

  /**
   * Functional lt (less then)
   */
  let lt$ = (leftSide, rightSide)   => () => 
    $$(leftSide) < $$(rightSide)


  /**
   * Functional add (+)
   */
  let add$ = (leftSide, rightSide) => () => 
    $$(leftSide) + $$(rightSide)

// My hand compiled Charm script:

  /**
   * Functional fib compiled
   */
  let fib$ = (n) => if$(                 // fib: (n) => if(
    lt$(n, 2),                           //   n < 2
    () => n,                             //   n
    () => add$(fib$(n-2), fib$(n-1))     //   fib(n-1) + fib(n-2)
  )                                      // )

// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));

// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))

// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable

https://jsfiddle.net/819Lgwtz/42/

How to calculate moving average without keeping the count and data-total?

Here's yet another answer offering commentary on how Muis, Abdullah Al-Ageel and Flip's answer are all mathematically the same thing except written differently.

Sure, we have José Manuel Ramos's analysis explaining how rounding errors affect each slightly differently, but that's implementation dependent and would change based on how each answer were applied to code.

There is however a rather big difference

It's in Muis's N, Flip's k, and Abdullah Al-Ageel's n. Abdullah Al-Ageel doesn't quite explain what n should be, but N and k differ in that N is "the number of samples where you want to average over" while k is the count of values sampled. (Although I have doubts to whether calling N the number of samples is accurate.)

And here we come to the answer below. It's essentially the same old exponential weighted moving average as the others, so if you were looking for an alternative, stop right here.

Exponential weighted moving average

Initially:

average = 0
counter = 0

For each value:

counter += 1
average = average + (value - average) / min(counter, FACTOR)

The difference is the min(counter, FACTOR) part. This is the same as saying min(Flip's k, Muis's N).

FACTOR is a constant that affects how quickly the average "catches up" to the latest trend. Smaller the number the faster. (At 1 it's no longer an average and just becomes the latest value.)

This answer requires the running counter counter. If problematic, the min(counter, FACTOR) can be replaced with just FACTOR, turning it into Muis's answer. The problem with doing this is the moving average is affected by whatever average is initiallized to. If it was initialized to 0, that zero can take a long time to work its way out of the average.

How it ends up looking

Exponential moving average

Can the Android layout folder contain subfolders?

You CAN do this with gradle. I've made a demo project showing how.

The trick is to use gradle's ability to merge multiple resource folders, and set the res folder as well as the nested subfolders in the sourceSets block.

The quirk is that you can't declare a container resource folder before you declare that folder's child resource folders.

Below is the sourceSets block from the build.gradle file from the demo. Notice that the subfolders are declared first.

sourceSets {
    main {
        res.srcDirs =
        [
                'src/main/res/layouts/layouts_category2',
                'src/main/res/layouts',
                'src/main/res'
        ]
    }
}

nested resources picture

Also, the direct parent of your actual resource files (pngs, xml layouts, etc..) does still need to correspond with the specification.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.

In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.

#pragma mark is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.

How to write a PHP ternary operator

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);