Programs & Examples On #Elements

Android ListView with onClick items

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent i = new Intent(getActivity(), DiscussAddValu.class);
        startActivity(i);
    }
});

How to set DOM element as the first child?

Unless I have misunderstood:

$("e").prepend("<yourelem>Text</yourelem>");

Or

$("<yourelem>Text</yourelem>").prependTo("e");

Although it sounds like from your description that there is some condition attached, so

if (SomeCondition){
    $("e").prepend("<yourelem>Text</yourelem>");
}
else{
    $("e").append("<yourelem>Text</yourelem>");
}

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

What's the best way to loop through a set of elements in JavaScript?

I prefer the for loop as it's more readable. Looping from length to 0 would be more efficient than looping from 0 to length. And using a reversed while loop is more efficient than a foor loop as you said. I don't have the link to the page with comparison results anymore but I remember that the difference varied on different browsers. For some browser the reversed while loop was twice as fast. However it makes no difference if you're looping "small" arrays. In your example case the length of elements will be "small"

Best way to get child nodes

The cross browser way to do is to use childNodes to get NodeList, then make an array of all nodes with nodeType ELEMENT_NODE.

/**
 * Return direct children elements.
 *
 * @param {HTMLElement}
 * @return {Array}
 */
function elementChildren (element) {
    var childNodes = element.childNodes,
        children = [],
        i = childNodes.length;

    while (i--) {
        if (childNodes[i].nodeType == 1) {
            children.unshift(childNodes[i]);
        }
    }

    return children;
}

http://jsfiddle.net/s4kxnahu/

This is especially easy if you are using a utility library such as lodash:

/**
 * Return direct children elements.
 *
 * @param {HTMLElement}
 * @return {Array}
 */
function elementChildren (element) {
    return _.where(element.childNodes, {nodeType: 1});
}

Future:

You can use querySelectorAll in combination with :scope pseudo-class (matches the element that is the reference point of the selector):

parentElement.querySelectorAll(':scope > *');

At the time of writing this :scope is supported in Chrome, Firefox and Safari.

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

Is it possible to clone html element objects in JavaScript / JQuery?

You need to select "#foo2" as your selector. Then, get it with html().

Here is the html:

<div id="foo1">

</div>
<div id="foo2">
    <div>Foo Here</div>
</div>?

Here is the javascript:

$("#foo2").click(function() {
    //alert("clicked");
    var value=$(this).html();
    $("#foo1").html(value);
});?

Here is the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

Number of elements in a javascript object

Although JS implementations might keep track of such a value internally, there's no standard way to get it.

In the past, Mozilla's Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5.

For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():

function countProperties(obj) {
    var count = 0;

    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            ++count;
    }

    return count;
}

In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)

function countProperties(obj) {
    return Object.keys(obj).length;
}

Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length).

If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.

How to return a specific element of an array?

You code should look like this:

public int getElement(int[] arrayOfInts, int index) {
    return arrayOfInts[index];
}

Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.

How to get span tag inside a div in jQuery and assign a text?

$("#message > span").text("your text");

or

$("#message").find("span").text("your text");

or

$("span","#message").text("your text");

or

$("#message > a.close-notify").siblings('span').text("your text");

Get multiple elements by Id

Use jquery multiple selector.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>

Link : http://api.jquery.com/multiple-selector/

selector should like this : $("#id1,#id2,#id3")

Skipping every other element after the first

def skip_elements(elements):
    # Initialize variables
    new_list = []
    i = 0

    # Iterate through the list
    for words in elements:
        # Does this element belong in the resulting list?
        if i <= len(elements):
            # Add this element to the resulting list
            new_list.insert(i,elements[i])
        # Increment i
        i += 2

    return new_list

'cl' is not recognized as an internal or external command,

You can use Command prompt for VS 2010 and then select the path that your boost located. Use "bootstrap.bat", you can successfully install it.

How to change a table name using an SQL query?

In Postgress SQL:

Alter table student rename to student_details;

IE8 css selector

I have a solution that I use only when I have to, after I build my html & css valid and working in most browsers, I do the occasional hack with this amazing piece of javascript from Rafael Lima. http://rafael.adm.br/css_browser_selector/

It keeps my CSS & HTML valid and clean, I know it's not the ideal solution, using javascript to fix hacks, but as long as your code is originally as close as possible (silly IE just breaks things sometimes) then moving something a few px with javascript isn't as big of a deal as some people think. Plus for time/cost reasons is a quick & easy fix.

Append a dictionary to a dictionary

A three-liner to combine or merge two dictionaries:

dest = {}
dest.update(orig)
dest.update(extra)

This creates a new dictionary dest without modifying orig and extra.

Note: If a key has different values in orig and extra, then extra overrides orig.

How to set width and height dynamically using jQuery

Try this:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

Bash Script : what does #!/bin/bash mean?

When the first characters in a script are #!, that is called the shebang. If your file starts with #!/path/to/something the standard is to run something and pass the rest of the file to that program as an input.

With that said, the difference between #!/bin/bash, #!/bin/sh, or even #!/bin/zsh is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash and sh are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh is a link to dash, and on traditional Unix systems (Solaris, Irix, etc) bash is usually a completely different program from sh.

Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python, #!/usr/bin/perl, or even #!/usr/local/bin/my_own_scripting_language.

Is floating point math broken?

My workaround:

function add(a, b, precision) {
    var x = Math.pow(10, precision || 2);
    return (Math.round(a * x) + Math.round(b * x)) / x;
}

precision refers to the number of digits you want to preserve after the decimal point during addition.

jQuery .val change doesn't change input value

to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426

http://api.jquery.com/val/#val2

about val()

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

docker-compose up for only certain containers

Update

Starting with docker-compose 1.28.0 the new service profiles are just made for that! With profiles you can mark services to be only started in specific profiles:

services:
  client:
    # ...
  db:
    # ...
  npm:
    profiles: ["cli-only"]
    # ...
docker-compose up # start main services, no npm
docker-compose run --rm npm # run npm service
docker-compose --profile cli-only # start main and all "cli-only" services

original answer

Since docker-compose v1.5 it is possible to pass multiple docker-compose.yml files with the -f flag. This allows you to split your dev tools into a separate docker-compose.yml which you then only include on-demand:

# start and attach to all your essential services
docker-compose up

# execute a defined command in docker-compose.dev.yml
docker-compose -f docker-compose.dev.yml run npm update

# if your command depends_on a service you need to include both configs
docker-compose -f docker-compose.yml -f docker-compose.dev.yml run npm update

For an in-depth discussion on this see docker/compose#1896.

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

If this issue is happening in Wildfly 8 and JDK1.8,then we need to specify MaxMetaSpace settings instead of PermGen settings.

For example we need to add below configuration in setenv.sh file of wildfly. JAVA_OPTS="$JAVA_OPTS -XX:MaxMetaspaceSize=256M"

For more information, please check Wildfly Heap Issue

window.open target _self v window.location.href?

Hopefully someone else is saved by reading this.

We encountered an issue with webkit based browsers doing:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

How to check if the URL contains a given string?

You need add href property and check indexOf instead of contains

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
  $(document).ready(function() {_x000D_
    if (window.location.href.indexOf("franky") > -1) {_x000D_
      alert("your url contains the name franky");_x000D_
    }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I size a UITextView to its content?

In iOS6, you can check the contentSize property of UITextView right after you set the text. In iOS7, this will no longer work. If you want to restore this behavior for iOS7, place the following code in a subclass of UITextView.

- (void)setText:(NSString *)text
{
    [super setText:text];

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
        UIEdgeInsets inset = self.textContainerInset;
        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
    }
}

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

libxml/tree.h no such file or directory

i tought i added wrongly, then i realize the problem is it not support arc, so check the support one here, life saver -> http://www.michaelbabiy.com/arc-compliant-gdataxml-library/

Click event on select option element in chrome

What usually works for me is to first change the value of the dropdown, e.g.

$('#selectorForOption').attr('selected','selected')

and then trigger the a change

$('#selectorForOption').changed()

This way, any javascript that is wired to

Most efficient method to groupby on an array of objects

_x000D_
_x000D_
/**
 * array group by 
 * @category array
 * @function arrayGroupBy
 * @returns  {object} {"fieldName":[{...}],...}
 * @static
 * @author hht
 * @param {string}} key group key
 * @param {array} data array
 *
 * @example example 01 
 * --------------------------------------------------------------------------
 * import { arrayGroupBy } from "@xx/utils";
 * const array =  [
 *  {
 *    type: 'assets',
 *    name: 'zhangsan',
 *    age: '33',
 *  },
 *  {
 *    type: 'config',
 *    name: 'a',
 *    age: '13',
 *  },
 *  {
 *    type: 'run',
 *    name: 'lisi',
 *    age: '3',
 *  },
 *  {
 *    type: 'xx',
 *    name: 'timo',
 *    age: '4',
 *  },
 *];
 * arrayGroupBy(array,'type',);
 *
 * result:{
 *    assets: [{ age: '33', name: 'zhangsan', type: 'assets' }],
 *    config: [{ age: '13', name: 'a', type: 'config' }],
 *    run: [{ age: '3', name: 'lisi', type: 'run' }],
 *    xx: [{ age: '4', name: 'timo', type: 'xx' }],
 *  };
 *
 * @example example 02 null
 * --------------------------------------------------------------------------
 * const array = null;
 * arrayGroupBy(array,"type");
 *
 * result:{}
 *
 * @example example 03 key undefind
 * --------------------------------------------------------------------------
 * const array =  [
 *  {
 *    type: 'assets',
 *    name: 'zhangsan',
 *    age: '33',
 *  },
 *  {
 *    type: 'config',
 *    name: 'a',
 *    age: '13',
 *  },
 *  {
 *    type: 'run',
 *    name: 'lisi',
 *    age: '3',
 *  },
 *  {
 *    type: 'xx',
 *    name: 'timo',
 *    age: '4',
 *  },
 *];
 * arrayGroupBy(array,"xx");
 *
 * {}
 *
 */
  const arrayGroupBy = (data, key) => {
  if (!data || !Array.isArray(data)) return {};
  const groupObj = {};
  data.forEach((item) => {
    if (!item[key]) return;
    const fieldName = item[key];
    if (!groupObj[fieldName]) {
      groupObj[fieldName] = [item];
      return;
    }
    groupObj[fieldName].push(item);
  });
  return groupObj;
};

const array = [
    {
      type: 'assets',
      name: 'zhangsan',
      age: '33',
    },
    {
      type: 'config',
      name: 'a',
      age: '13',
    },
    {
      type: 'run',
      name: 'lisi',
      age: '3',
    },
    {
      type: 'run',
      name: 'wangmazi',
      age: '3',
    },
    {
      type: 'xx',
      name: 'timo',
      age: '4',
    },
  ];
console.dir(arrayGroupBy(array, 'type'))
_x000D_
<p>


describe('arrayGroupBy match', () => {
  const array = [
    {
      type: 'assets',
      name: 'zhangsan',
      age: '33',
    },
    {
      type: 'config',
      name: 'a',
      age: '13',
    },
    {
      type: 'run',
      name: 'lisi',
      age: '3',
    },
    {
      type: 'xx',
      name: 'timo',
      age: '4',
    },
  ];

  test('arrayGroupBy  ...', () => {
    const result = {
      assets: [{ age: '33', name: 'zhangsan', type: 'assets' }],
      config: [{ age: '13', name: 'a', type: 'config' }],
      run: [{ age: '3', name: 'lisi', type: 'run' }],
      xx: [{ age: '4', name: 'timo', type: 'xx' }],
    };

    expect(arrayGroupBy(array, 'type')).toEqual(result);
  });

  test('arrayGroupBy not match..', () => {
    // result
    expect(arrayGroupBy(array, 'xx')).toEqual({});
  });

  test('arrayGroupBy null', () => {
    let array = null;
    expect(arrayGroupBy(array, 'type')).toEqual({});
  });

  test('arrayGroupBy undefined', () => {
    let array = undefined;
    expect(arrayGroupBy(array, 'type')).toEqual({});
  });

  test('arrayGroupBy empty', () => {
    let array = [];
    expect(arrayGroupBy(array, 'type')).toEqual({});
  });
});

</p>
_x000D_
_x000D_
_x000D_

MongoDB: Combine data from multiple collections into one..how?

Although you can't do this real-time, you can run map-reduce multiple times to merge data together by using the "reduce" out option in MongoDB 1.8+ map/reduce (see http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Outputoptions). You need to have some key in both collections that you can use as an _id.

For example, let's say you have a users collection and a comments collection and you want to have a new collection that has some user demographic info for each comment.

Let's say the users collection has the following fields:

  • _id
  • firstName
  • lastName
  • country
  • gender
  • age

And then the comments collection has the following fields:

  • _id
  • userId
  • comment
  • created

You would do this map/reduce:

var mapUsers, mapComments, reduce;
db.users_comments.remove();

// setup sample data - wouldn't actually use this in production
db.users.remove();
db.comments.remove();
db.users.save({firstName:"Rich",lastName:"S",gender:"M",country:"CA",age:"18"});
db.users.save({firstName:"Rob",lastName:"M",gender:"M",country:"US",age:"25"});
db.users.save({firstName:"Sarah",lastName:"T",gender:"F",country:"US",age:"13"});
var users = db.users.find();
db.comments.save({userId: users[0]._id, "comment": "Hey, what's up?", created: new ISODate()});
db.comments.save({userId: users[1]._id, "comment": "Not much", created: new ISODate()});
db.comments.save({userId: users[0]._id, "comment": "Cool", created: new ISODate()});
// end sample data setup

mapUsers = function() {
    var values = {
        country: this.country,
        gender: this.gender,
        age: this.age
    };
    emit(this._id, values);
};
mapComments = function() {
    var values = {
        commentId: this._id,
        comment: this.comment,
        created: this.created
    };
    emit(this.userId, values);
};
reduce = function(k, values) {
    var result = {}, commentFields = {
        "commentId": '', 
        "comment": '',
        "created": ''
    };
    values.forEach(function(value) {
        var field;
        if ("comment" in value) {
            if (!("comments" in result)) {
                result.comments = [];
            }
            result.comments.push(value);
        } else if ("comments" in value) {
            if (!("comments" in result)) {
                result.comments = [];
            }
            result.comments.push.apply(result.comments, value.comments);
        }
        for (field in value) {
            if (value.hasOwnProperty(field) && !(field in commentFields)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};
db.users.mapReduce(mapUsers, reduce, {"out": {"reduce": "users_comments"}});
db.comments.mapReduce(mapComments, reduce, {"out": {"reduce": "users_comments"}});
db.users_comments.find().pretty(); // see the resulting collection

At this point, you will have a new collection called users_comments that contains the merged data and you can now use that. These reduced collections all have _id which is the key you were emitting in your map functions and then all of the values are a sub-object inside the value key - the values aren't at the top level of these reduced documents.

This is a somewhat simple example. You can repeat this with more collections as much as you want to keep building up the reduced collection. You could also do summaries and aggregations of data in the process. Likely you would define more than one reduce function as the logic for aggregating and preserving existing fields gets more complex.

You'll also note that there is now one document for each user with all of that user's comments in an array. If we were merging data that has a one-to-one relationship rather than one-to-many, it would be flat and you could simply use a reduce function like this:

reduce = function(k, values) {
    var result = {};
    values.forEach(function(value) {
        var field;
        for (field in value) {
            if (value.hasOwnProperty(field)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};

If you want to flatten the users_comments collection so it's one document per comment, additionally run this:

var map, reduce;
map = function() {
    var debug = function(value) {
        var field;
        for (field in value) {
            print(field + ": " + value[field]);
        }
    };
    debug(this);
    var that = this;
    if ("comments" in this.value) {
        this.value.comments.forEach(function(value) {
            emit(value.commentId, {
                userId: that._id,
                country: that.value.country,
                age: that.value.age,
                comment: value.comment,
                created: value.created,
            });
        });
    }
};
reduce = function(k, values) {
    var result = {};
    values.forEach(function(value) {
        var field;
        for (field in value) {
            if (value.hasOwnProperty(field)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};
db.users_comments.mapReduce(map, reduce, {"out": "comments_with_demographics"});

This technique should definitely not be performed on the fly. It's suited for a cron job or something like that which updates the merged data periodically. You'll probably want to run ensureIndex on the new collection to make sure queries you perform against it run quickly (keep in mind that your data is still inside a value key, so if you were to index comments_with_demographics on the comment created time, it would be db.comments_with_demographics.ensureIndex({"value.created": 1});

Mix Razor and Javascript code

A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.

Index.cshtml

<div id="Result">
</div>

<button id="btnLoad">Click me</button>

@section scripts
{
    @Html.Partial("Scripts")
}

Scripts.cshtml

<script type="text/javascript">
    var url = "@Url.Action("Index", "Home")";

    $(document).ready(function() {
        $("#btnLoad").click(function() {
            $.ajax({
                type: "POST",
                url: url ,
                data: {someParameter: "some value"},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

Move the mouse pointer to a specific position?

So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.

Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock

And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/

Optional query string parameters in ASP.NET Web API

It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

public class BooksController : ApiController
  {
    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks([FromUri]BookQuery query)
    {
      // ...
    }
  }

  public class BookQuery
  {
    public string Author { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public string SomethingElse { get; set; }
    public DateTime? Date { get; set; }
  }

It even supports multiple parameters, as long as the properties don't conflict.

// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
  // ...
}

public class Paging
{
  public string Sort { get; set; }
  public int Skip { get; set; }
  public int Take { get; set; }
}

Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

StringUtils.isBlank() vs String.isEmpty()

StringUtils isEmpty = String isEmpty checks + checks for null.

StringUtils isBlank = StringUtils isEmpty checks + checks if the text contains only whitespace character(s).

Useful links for further investigation:

When should I use "this" in a class?

this is useful in the builder pattern.

public class User {

    private String firstName;
    private String surname;

    public User(Builder builder){
        firstName = builder.firstName;
        surname = builder.surname;
    }

    public String getFirstName(){
        return firstName;
    }

    public String getSurname(){
        return surname;
    }

    public static class Builder {
        private String firstName;
        private String surname;

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setSurname(String surname) {
            this.surname = surname;
            return this;
        }

        public User build(){
            return new User(this);
        }

    }

    public static void main(String[] args) {
        User.Builder builder = new User.Builder();
        User user = builder.setFirstName("John").setSurname("Doe").build();
    }

}

How to find all the subclasses of a class given its name?

This isn't as good an answer as using the special built-in __subclasses__() class method which @unutbu mentions, so I present it merely as an exercise. The subclasses() function defined returns a dictionary which maps all the subclass names to the subclasses themselves.

def traced_subclass(baseclass):
    class _SubclassTracer(type):
        def __new__(cls, classname, bases, classdict):
            obj = type(classname, bases, classdict)
            if baseclass in bases: # sanity check
                attrname = '_%s__derived' % baseclass.__name__
                derived = getattr(baseclass, attrname, {})
                derived.update( {classname:obj} )
                setattr(baseclass, attrname, derived)
             return obj
    return _SubclassTracer

def subclasses(baseclass):
    attrname = '_%s__derived' % baseclass.__name__
    return getattr(baseclass, attrname, None)


class BaseClass(object):
    pass

class SubclassA(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

class SubclassB(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

print subclasses(BaseClass)

Output:

{'SubclassB': <class '__main__.SubclassB'>,
 'SubclassA': <class '__main__.SubclassA'>}

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

Practical uses of different data structures

I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out

mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks, but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.

The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:

  • pros and cons of the common data structures
  • why each data structure exist
  • how it actually work in the memory
  • specific questions/exercises and deciding which structure to use for maximum efficiency
  • lucid Big 0 explanation

I also posted notes on github if you are interested.

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

How to use readline() method in Java?

I advise you to go with Scanner instead of DataInputStream. Scanner is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner.

Example

Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to loop through a checkboxlist and to find what's checked and not checked?

for (int i = 0; i < clbIncludes.Items.Count; i++)
  if (clbIncludes.GetItemChecked(i))
    // Do selected stuff
  else
    // Do unselected stuff

If the the check is in indeterminate state, this will still return true. You may want to replace

if (clbIncludes.GetItemChecked(i))

with

if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)

if you want to only include actually checked items.

How to vertically align a html radio button to it's label?

label, input {
    vertical-align: middle;
}

I'm just align the vertical midpoint of the boxes with the baseline of the parent box plus half the x-height (en.wikipedia.org/wiki/X-height) of the parent.

not finding android sdk (Unity)

Easier solution: set the environment variable USE_SDK_WRAPPER=1, or hack tools/android.bat to add the line "set USE_SDK_WRAPPER=1". This prevents android.bat from popping up a "y/n" prompt, which is what's confusing Unity.

Struct inheritance in C++

Other than what Alex and Evan have already stated, I would like to add that a C++ struct is not like a C struct.

In C++, a struct can have methods, inheritance, etc. just like a C++ class.

Inline for loop

your list comphresnion will, work but will return list of None because append return None:

demo:

>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

better way to use it like this:

>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

R define dimensions of empty data frame

Just create a data frame of empty vectors:

collect1 <- data.frame(id = character(0), max1 = numeric(0), max2 = numeric(0))

But if you know how many rows you're going to have in advance, you should just create the data frame with that many rows to start with.

How to center an element horizontally and vertically

The best way to center a box both vertically and horizontally, is to use two containers :

##The outher container :

  • should have display: table;

##The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

##The content box :

  • should have display: inline-block;
  • should adjust the horizontal text-alignment, unless you want text to be centered

##Demo :

_x000D_
_x000D_
body {
    margin : 0;
}

.outer-container {
    display: table;
    width: 80%;
    height: 120px;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

##Centering in the middle of the page:

To center your content in the middle of your page, add the following to your outer container :

  • position : absolute;
  • width: 100%;
  • height: 100%;

Here's a demo for that :

_x000D_
_x000D_
body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

Animate a custom Dialog

I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.

  1. Inside res/style.xml

    <style name="AppTheme" parent="android:Theme.Light" />
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
    </style>
    
    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>
    

  2. Inside anim/fadein.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
    
  3. Inside anim/fadeout.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/anticipate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
    
  4. MainActivity

    Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
    

CSS3 transform not working

-webkit-transform is no more needed

ms already support rotation ( -ms-transform: rotate(-10deg); )

try this:

li a {
   ...

    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
    }

How to rename JSON key

JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.

In reviver function:

  • if we return undefined, the original property will be deleted.
  • this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.
const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}]';

const obj = JSON.parse(json, function(k, v) {
    if (k === "_id") {
        this.id = v;
        return; # if return  undefined, orignal property will be removed
    }
    return v;
});

const res = JSON.stringify(obj);
console.log(res)

output:

[{"email":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"[email protected]","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

Controlling fps with requestAnimationFrame?

Skipping requestAnimationFrame cause not smooth(desired) animation at custom fps.

_x000D_
_x000D_
// Input/output DOM elements_x000D_
var $results = $("#results");_x000D_
var $fps = $("#fps");_x000D_
var $period = $("#period");_x000D_
_x000D_
// Array of FPS samples for graphing_x000D_
_x000D_
// Animation state/parameters_x000D_
var fpsInterval, lastDrawTime, frameCount_timed, frameCount, lastSampleTime, _x000D_
  currentFps=0, currentFps_timed=0;_x000D_
var intervalID, requestID;_x000D_
_x000D_
// Setup canvas being animated_x000D_
var canvas = document.getElementById("c");_x000D_
var canvas_timed = document.getElementById("c2");_x000D_
canvas_timed.width = canvas.width = 300;_x000D_
canvas_timed.height = canvas.height = 300;_x000D_
var ctx = canvas.getContext("2d");_x000D_
var ctx2 = canvas_timed.getContext("2d");_x000D_
_x000D_
_x000D_
// Setup input event handlers_x000D_
_x000D_
$fps.on('click change keyup', function() {_x000D_
    if (this.value > 0) {_x000D_
        fpsInterval = 1000 / +this.value;_x000D_
    }_x000D_
});_x000D_
_x000D_
$period.on('click change keyup', function() {_x000D_
    if (this.value > 0) {_x000D_
        if (intervalID) {_x000D_
            clearInterval(intervalID);_x000D_
        }_x000D_
        intervalID = setInterval(sampleFps, +this.value);_x000D_
    }_x000D_
});_x000D_
_x000D_
_x000D_
function startAnimating(fps, sampleFreq) {_x000D_
_x000D_
    ctx.fillStyle = ctx2.fillStyle = "#000";_x000D_
    ctx.fillRect(0, 0, canvas.width, canvas.height);_x000D_
    ctx2.fillRect(0, 0, canvas.width, canvas.height);_x000D_
    ctx2.font = ctx.font = "32px sans";_x000D_
    _x000D_
    fpsInterval = 1000 / fps;_x000D_
    lastDrawTime = performance.now();_x000D_
    lastSampleTime = lastDrawTime;_x000D_
    frameCount = 0;_x000D_
    frameCount_timed = 0;_x000D_
    animate();_x000D_
    _x000D_
    intervalID = setInterval(sampleFps, sampleFreq);_x000D_
  animate_timed()_x000D_
}_x000D_
_x000D_
function sampleFps() {_x000D_
    // sample FPS_x000D_
    var now = performance.now();_x000D_
    if (frameCount > 0) {_x000D_
        currentFps =_x000D_
            (frameCount / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
        currentFps_timed =_x000D_
            (frameCount_timed / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
        $results.text(currentFps + " | " + currentFps_timed);_x000D_
        _x000D_
        frameCount = 0;_x000D_
        frameCount_timed = 0;_x000D_
    }_x000D_
    lastSampleTime = now;_x000D_
}_x000D_
_x000D_
function drawNextFrame(now, canvas, ctx, fpsCount) {_x000D_
    // Just draw an oscillating seconds-hand_x000D_
    _x000D_
    var length = Math.min(canvas.width, canvas.height) / 2.1;_x000D_
    var step = 15000;_x000D_
    var theta = (now % step) / step * 2 * Math.PI;_x000D_
_x000D_
    var xCenter = canvas.width / 2;_x000D_
    var yCenter = canvas.height / 2;_x000D_
    _x000D_
    var x = xCenter + length * Math.cos(theta);_x000D_
    var y = yCenter + length * Math.sin(theta);_x000D_
    _x000D_
    ctx.beginPath();_x000D_
    ctx.moveTo(xCenter, yCenter);_x000D_
    ctx.lineTo(x, y);_x000D_
   ctx.fillStyle = ctx.strokeStyle = 'white';_x000D_
    ctx.stroke();_x000D_
    _x000D_
    var theta2 = theta + 3.14/6;_x000D_
    _x000D_
    ctx.beginPath();_x000D_
    ctx.moveTo(xCenter, yCenter);_x000D_
    ctx.lineTo(x, y);_x000D_
    ctx.arc(xCenter, yCenter, length*2, theta, theta2);_x000D_
_x000D_
    ctx.fillStyle = "rgba(0,0,0,.1)"_x000D_
    ctx.fill();_x000D_
    _x000D_
    ctx.fillStyle = "#000";_x000D_
    ctx.fillRect(0,0,100,30);_x000D_
    _x000D_
    ctx.fillStyle = "#080";_x000D_
    ctx.fillText(fpsCount,10,30);_x000D_
}_x000D_
_x000D_
// redraw second canvas each fpsInterval (1000/fps)_x000D_
function animate_timed() {_x000D_
    frameCount_timed++;_x000D_
    drawNextFrame( performance.now(), canvas_timed, ctx2, currentFps_timed);_x000D_
    _x000D_
    setTimeout(animate_timed, fpsInterval);_x000D_
}_x000D_
_x000D_
function animate(now) {_x000D_
    // request another frame_x000D_
    requestAnimationFrame(animate);_x000D_
    _x000D_
    // calc elapsed time since last loop_x000D_
    var elapsed = now - lastDrawTime;_x000D_
_x000D_
    // if enough time has elapsed, draw the next frame_x000D_
    if (elapsed > fpsInterval) {_x000D_
        // Get ready for next frame by setting lastDrawTime=now, but..._x000D_
        // Also, adjust for fpsInterval not being multiple of 16.67_x000D_
        lastDrawTime = now - (elapsed % fpsInterval);_x000D_
_x000D_
        frameCount++;_x000D_
      drawNextFrame(now, canvas, ctx, currentFps);_x000D_
    }_x000D_
}_x000D_
startAnimating(+$fps.val(), +$period.val());
_x000D_
input{_x000D_
  width:100px;_x000D_
}_x000D_
#tvs{_x000D_
  color:red;_x000D_
  padding:0px 25px;_x000D_
}_x000D_
H3{_x000D_
  font-weight:400;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>requestAnimationFrame skipping <span id="tvs">vs.</span> setTimeout() redraw</h3>_x000D_
<div>_x000D_
    <input id="fps" type="number" value="33"/> FPS:_x000D_
    <span id="results"></span>_x000D_
</div>_x000D_
<div>_x000D_
    <input id="period" type="number" value="1000"/> Sample period (fps, ms)_x000D_
</div>_x000D_
<canvas id="c"></canvas><canvas id="c2"></canvas>
_x000D_
_x000D_
_x000D_

Original code by @tavnab.

Converting string to double in C#

Most people already tried to answer your questions.
If you are still debugging, have you thought about using:

Double.TryParse(String, Double);

This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:

Double.TryParse(String, NumberStyles, IFormatProvider, Double);

This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.

If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

Hope that helps.

How can I create my own comparator for a map?

Yes, the 3rd template parameter on map specifies the comparator, which is a binary predicate. Example:

struct ByLength : public std::binary_function<string, string, bool>
{
    bool operator()(const string& lhs, const string& rhs) const
    {
        return lhs.length() < rhs.length();
    }
};

int main()
{
    typedef map<string, string, ByLength> lenmap;
    lenmap mymap;

    mymap["one"] = "one";
    mymap["a"] = "a";
    mymap["fewbahr"] = "foobar";

    for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
        cout << it->first << "\n";
}

How can I do time/hours arithmetic in Google Spreadsheet?

Example of calculating time:

work-start   work-stop   lunchbreak    effective time

  07:30:00    17:00:00          1.5                 8  [=((A2-A1)*24)-A3]

If you subtract one time value from another the result you get will represent the fraction of 24 hours, so if you multiply the result with 24 you get the value represented in hours.

In other words: the operation is mutiply, but the meaning is to change the format of the number (from days to hours).

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

sendmail: how to configure sendmail on ubuntu?

I got the top answer working (can't reply yet) after one small edit

This did not work for me:

FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl

The first single quote for each string should be changed to a backtick (`) like this:

FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

After the change I run:

sudo sendmailconfig

And I'm in business :)

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

Android - border for button

Step 1 : Create file named : my_button_bg.xml

Step 2 : Place this file in res/drawables.xml

Step 3 : Insert below code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF" 
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="5px" android:color="#000000" />
</shape>

Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your Text"
    android:background="@drawable/my_button_bg"
    />

How to print GETDATE() in SQL Server with milliseconds in time?

This is equivalent to new Date().getTime() in JavaScript :

Use the below statement to get the time in seconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)

Use the below statement to get the time in milliseconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)  * 1000

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

How to change MySQL data directory?

Everything as @user1341296 said, plus...

You better not to change /etc/mysql/my.cnf Instead you want to create new file/etc/mysql/conf.d/ext.cnf (any name, but extension should be cnf)

And put in it your change:

[mysqld]
datadir=/vagrant/mq/mysql

In this way

  • You do not need to change existing file (easier for automation scripts)
  • No problems with MySQL version (and it's configs!) update.

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

How to thoroughly purge and reinstall postgresql on ubuntu?

Option A

If your install isn't already damaged, you can drop unwanted PostgreSQL servers ("clusters") using pg_dropcluster. Use that in preference to a full purge and reinstall if you just want to restart with a fresh PostgreSQL instance.

$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
11  main    5432 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
$ sudo systemctl stop postgresql@11-main
$ sudo pg_dropcluster --stop 11 main
$ sudo pg_createcluster --start 11 main

Option B

If you really need to do a full purge and reinstall, first make sure PostgreSQL isn't running. ps -C postgres should show no results.

Now run:

apt-get --purge remove postgresql\*

to remove everything PostgreSQL from your system. Just purging the postgres package isn't enough since it's just an empty meta-package.

Once all PostgreSQL packages have been removed, run:

rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

You should now be able to:

apt-get install postgresql

or for a complete install:

apt-get install postgresql-8.4 postgresql-contrib-8.4 postgresql-doc-8.4

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:

Class.forName("Somthing");

2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:

Class.forName("Somthing").newInstance();

C Macro definition to determine big endian or little endian machine?

Please pay attention that most of the answers here are not portable, since compilers today will evaluate those answers in compilation time (depends on the optimization) and return a specific value based on a specific endianness, while the actual machine endianness can differ. The values on which the endianness is tested, won't never reach the system memory thus the real executed code will return the same result regardless of the actual endianness.

For example, in ARM Cortex-M3 the implemented endianness will reflect in a status bit AIRCR.ENDIANNESS and compiler cannot know this value in compile time.

Compilation output for some of the answers suggested here:

https://godbolt.org/z/GJGNE2 for this answer,

https://godbolt.org/z/Yv-pyJ for this answer, and so on.

To solve it you will need to use the volatile qualifier. Yogeesh H T's answer is the closest one for today's real life usage, but since Christoph suggests more comprehensive solution, a slight fix to his answer would make the answer complete, just add volatile to the union declaration: static const volatile union.

This would assure storing and reading from memory, which is needed to determine endianness.

Private pages for a private Github repo

You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.

Demonstration

How to set the From email address for mailx command?

You can use the "-r" option to set the sender address:

mailx -r [email protected] -s ...

Find all files in a directory with extension .txt in Python

Here's one with extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))

How to align texts inside of an input?

The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this:

<input type="text" class="text-right"/> 
<input type="number" class="text-right"/>

As a note this works on other input types as well, like numeric as shown above.

If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.

.text-right{
    text-align: right;
}

Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

Finding height in Binary Search Tree

In my opinion, your code would benefit from being simplified a bit. Rather than attempting to end the recursion when a child pointer is null, only end it when the current pointer is null. That makes the code a lot simpler to write. In pseudo-code, it looks something like this:

if (node = null)
    return 0;
else
    left = height(node->left);
    right = height(node->right);
    return 1 + max(left, right);

What's a concise way to check that environment variables are set in a Unix shell script?

We can write a nice assertion to check a bunch of variables all at once:

#
# assert if variables are set (to a non-empty string)
# if any variable is not set, exit 1 (when -f option is set) or return 1 otherwise
#
# Usage: assert_var_not_null [-f] variable ...
#
function assert_var_not_null() {
  local fatal var num_null=0
  [[ "$1" = "-f" ]] && { shift; fatal=1; }
  for var in "$@"; do
    [[ -z "${!var}" ]] &&
      printf '%s\n' "Variable '$var' not set" >&2 &&
      ((num_null++))
  done

  if ((num_null > 0)); then
    [[ "$fatal" ]] && exit 1
    return 1
  fi
  return 0
}

Sample invocation:

one=1 two=2
assert_var_not_null one two
echo test 1: return_code=$?
assert_var_not_null one two three
echo test 2: return_code=$?
assert_var_not_null -f one two three
echo test 3: return_code=$? # this code shouldn't execute

Output:

test 1: return_code=0
Variable 'three' not set
test 2: return_code=1
Variable 'three' not set

More such assertions here: https://github.com/codeforester/base/blob/master/lib/assertions.sh

Android- create JSON Array and JSON Object

Use the following code:

JSONObject student1 = new JSONObject();
try {
    student1.put("id", "3");
    student1.put("name", "NAME OF STUDENT");
    student1.put("year", "3rd");
    student1.put("curriculum", "Arts");
    student1.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JSONObject student2 = new JSONObject();
try {
    student2.put("id", "2");
    student2.put("name", "NAME OF STUDENT2");
    student2.put("year", "4rd");
    student2.put("curriculum", "scicence");
    student2.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


JSONArray jsonArray = new JSONArray();

jsonArray.put(student1);
jsonArray.put(student2);

JSONObject studentsObj = new JSONObject();
    studentsObj.put("Students", jsonArray);



String jsonStr = studentsObj.toString();

    System.out.println("jsonString: "+jsonStr);

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

Accessing an array out of bounds gives no error, why?

It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).

Use std::vector with std::vector::iterator's instead so you don't have to worry about it.

Edit:

Just for fun, run this and see how long until you crash:

int main()
{
   int array[1];

   for (int i = 0; i != 100000; i++)
   {
       array[i] = i;
   }

   return 0; //will be lucky to ever reach this
}

Edit2:

Don't run that.

Edit3:

OK, here is a quick lesson on arrays and their relationships with pointers:

When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.

When you have a pointer to an array, like this:

int array[5];
int *ptr = array;

Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:

int *ptr = &array[0];

When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:

int main()
{
   int array[1];
   int *ptr = array;

   for (int i = 0; i != 100000; i++, ptr++)
   {
       *ptr++ = i;
   }

   return 0; //will be lucky to ever reach this
}

The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

What does yield mean in PHP?

None of the answers above show a concrete example using massive arrays populated by non-numeric members. Here is an example using an array generated by explode() on a large .txt file (262MB in my use case):

<?php

ini_set('memory_limit','1000M');

echo "Starting memory usage: " . memory_get_usage() . "<br>";

$path = './file.txt';
$content = file_get_contents($path);

foreach(explode("\n", $content) as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output was:

Starting memory usage: 415160
Final memory usage: 270948256

Now compare that to a similar script, using the yield keyword:

<?php

ini_set('memory_limit','1000M');

echo "Starting memory usage: " . memory_get_usage() . "<br>";

function x() {
    $path = './file.txt';
    $content = file_get_contents($path);
    foreach(explode("\n", $content) as $x) {
        yield $x;
    }
}

foreach(x() as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output for this script was:

Starting memory usage: 415152
Final memory usage: 415616

Clearly memory usage savings were considerable (?MemoryUsage -----> ~270.5 MB in first example, ~450B in second example).

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Seeing all other answers. I found for me a simpler way.

I just removed all lines in the .classpath (editing with eclipse) containing a var and used maven -> update project without an error.

How do I find out if the GPS of an Android device is enabled

GPS will be used if the user has allowed it to be used in its settings.

You can't explicitly switch this on anymore, but you don't have to - it's a privacy setting really, so you don't want to tweak it. If the user is OK with apps getting precise co-ordinates it'll be on. Then the location manager API will use GPS if it can.

If your app really isn't useful without GPS, and it's off, you can open the settings app at the right screen using an intent so the user can enable it.

How can you test if an object has a specific property?

Try this for a one liner that is strict safe.

[bool]$myobject.PSObject.Properties[$propertyName]

For example:

Set-StrictMode -Version latest;
$propertyName = 'Property1';
$myobject = [PSCustomObject]@{ Property0 = 'Value0' };

if ([bool]$myobject.PSObject.Properties[$propertyName]) {
    $value = $myobject.$propertyName;
}

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

CSS to hide INPUT BUTTON value text

Instead, just do a hook_form_alter and make the button an image button and you are done!

Distinct pair of values SQL

What you mean is either

SELECT DISTINCT a, b FROM pairs;

or

SELECT a, b FROM pairs GROUP BY a, b;

Request is not available in this context

Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.

Here's what I'm using when not in Classic Mode. The overhead is negligible.

/// <summary>
/// Class is called only on the first request
/// </summary>
private class AppStart
{
    static bool _init = false;
    private static Object _lock = new Object();

    /// <summary>
    /// Does nothing after first request
    /// </summary>
    /// <param name="context"></param>
    public static void Start(HttpContext context)
    {
        if (_init)
        {
            return;
        }
        //create class level lock in case multiple sessions start simultaneously
        lock (_lock)
        {
            if (!_init)
            {
                string server = context.Request.ServerVariables["SERVER_NAME"];
                string port = context.Request.ServerVariables["SERVER_PORT"];
                HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
                _init = true;
            }
        }
    }
}

protected void Session_Start(object sender, EventArgs e)
{
    //initializes Cache on first request
    AppStart.Start(HttpContext.Current);
}

Compression/Decompression string with C#

With the advent of .NET 4.0 (and higher) with the Stream.CopyTo() methods, I thought I would post an updated approach.

I also think the below version is useful as a clear example of a self-contained class for compressing regular strings to Base64 encoded strings, and vice versa:

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Here’s another approach using the extension methods technique to extend the String class to add string compression and decompression. You can drop the class below into an existing project and then use thusly:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

and

var decompressedString = compressedString.Decompress();

To wit:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

Is there a way to automatically generate getters and setters in Eclipse?

  • For All variable ALT+SHIFT+S Then R and for select all Press ALT+A

  • For Single variable Point cursor on the variable then press CTRL+1 and go for the second option from suggestions

ScreenShot

jQuery select box validation

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                required: true,
            }
        }
    });

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

window.print() not working in IE

Add these lines after newWin.document.write(divToPrint.innerHTML)

newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();

Then print function will work in all browser...

Pure CSS collapse/expand div

Or a super simple version with barely any css :)

<style>   
.faq ul li {
    display:block;
    float:left;
    padding:5px;
}

.faq ul li div {
    display:none;
}

.faq ul li div:target {
    display:block;
}


</style>


<div class="faq">
   <ul>
   <li><a href="#question1">Question 1</a>   
   <div id="question1">Answer 1 </div>
   </li>


   <li><a href="#question2">Question 2</a>
   <div id="question2">Answer 2 </div>
   </li>
   <li><a href="#question3">Question 3</a>
   <div id="question3">Answer 3 </div>
   </li>
   <li><a href="#question4">Question 4</a>
   <div id="question4">Answer 4 </div>
   </li>
   <li><a href="#question5">Question 5</a>
   <div id="question5">Answer 5 </div>
   </li>
   <li><a href="#question6">Question 6</a>
   <div id="question6">Answer 6 </div>
   </li>
   </ul>  
</div>

http://jsfiddle.net/ionko22/4sKD3/

How can I download a file from a URL and save it in Rails?

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation

Associative arrays in Shell scripts

I've found it true, as already mentioned, that the best performing method is to write out key/vals to a file, and then use grep/awk to retrieve them. It sounds like all sorts of unnecessary IO, but disk cache kicks in and makes it extremely efficient -- much faster than trying to store them in memory using one of the above methods (as the benchmarks show).

Here's a quick, clean method I like:

hinit() {
    rm -f /tmp/hashmap.$1
}

hput() {
    echo "$2 $3" >> /tmp/hashmap.$1
}

hget() {
    grep "^$2 " /tmp/hashmap.$1 | awk '{ print $2 };'
}

hinit capitols
hput capitols France Paris
hput capitols Netherlands Amsterdam
hput capitols Spain Madrid

echo `hget capitols France` and `hget capitols Netherlands` and `hget capitols Spain`

If you wanted to enforce single-value per key, you could also do a little grep/sed action in hput().

JavaScript unit test tools for TDD

We added JUnit integration to our Java to Javascript code generator ST-JS (http://st-js.org). The framework generates to corresponding Javascript for both the tested code and the unit tests and sends the code to different browsers.

There is no need for a separate server as the unit test runner opens the needed http port (and closes it once the tests finished). The framework manipulates the Java stacktrace so that the failed asserts are correctly displayed by the JUnit Eclipse plugin. Here is a simple example with jQuery and Mockjax:

@RunWith(STJSTestDriverRunner.class)
@HTMLFixture("<div id='fortune'></div>")

@Scripts({ "classpath://jquery.js",
       "classpath://jquery.mockjax.js", "classpath://json2.js" })
public class MockjaxExampleTest {
  @Test
  public void myTest() {
    $.ajaxSetup($map("async", false));
    $.mockjax(new MockjaxOptions() {
      {
        url = "/restful/fortune";
        responseText = new Fortune() {
          {
            status = "success";
            fortune = "Are you a turtle?";
          }
        };
      }
    });

    $.getJSON("/restful/fortune", null, new Callback3<Fortune, String, JQueryXHR>() {
      @Override
      public void $invoke(Fortune response, String p2, JQueryXHR p3) {
        if (response.status.equals("success")) {
          $("#fortune").html("Your fortune is: " + response.fortune);
        } else {
          $("#fortune").html("Things do not look good, no fortune was told");
        }

      }
    });
    assertEquals("Your fortune is: Are you a turtle?", $("#fortune").html());
  }

  private static class Fortune {
    public String status;
    public String fortune;
  }
}

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

how to bind datatable to datagridview in c#

Even better:

DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();

ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;

ServersTable.DataSource = SBind;
ServersTable.Refresh();

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.

How to convert milliseconds into human readable form?

A solution using awk:

$ ms=10000001; awk -v ms=$ms 'BEGIN {x=ms/1000; 
                                     s=x%60; x/=60;
                                     m=x%60; x/=60;
                                     h=x%60;
                              printf("%02d:%02d:%02d.%03d\n", h, m, s, ms%1000)}'
02:46:40.001

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

Returning Arrays in Java

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...

Removing items from a list

You cannot do it because you are already looping on it.

Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...

List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
   Object o = i.next();
  //some condition
    i.remove();
}

Is there a naming convention for MySQL?

MySQL has a short description of their more or less strict rules:

https://dev.mysql.com/doc/internals/en/coding-style.html

Most common codingstyle for MySQL by Simon Holywell:

http://www.sqlstyle.guide/

See also this question: Are there any published coding style guidelines for SQL?

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

hidden field in php

Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).

Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

Append date to filename in linux

cp somefile somefile_`date +%d%b%Y`

C++ Singleton design pattern

The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.

Remove old Fragment from fragment manager

I had the same issue to remove old fragments. I ended up clearing the layout that contained the fragments.

LinearLayout layout = (LinearLayout) a.findViewById(R.id.layoutDeviceList);
layout.removeAllViewsInLayout();
FragmentTransaction ft = getFragmentManager().beginTransaction();
...

I do not know if this creates leaks, but it works for me.

Regex pattern including all special characters

I have defined one pattern to look for any of the ASCII Special Characters ranging between 032 to 126 except the alpha-numeric. You may use something like the one below:

To find any Special Character:

[ -\/:-@\[-\`{-~]

To find minimum of 1 and maximum of any count:

(?=.*[ -\/:-@\[-\`{-~]{1,})

These patterns have Special Characters ranging between 032 to 047, 058 to 064, 091 to 096, and 123 to 126.

Can you style html form buttons with css?

You might want to add:

-webkit-appearance: none; 

if you need it looking consistent on Mobile Safari...

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

iPhone UIView Animation Best Practice

The difference seems to be the amount of control you need over the animation.

The CATransition approach gives you more control and therefore more things to set up, eg. the timing function. Being an object, you can store it for later, refactor to point all your animations at it to reduce duplicated code, etc.

The UIView class methods are convenience methods for common animations, but are more limited than CATransition. For example, there are only four possible transition types (flip left, flip right, curl up, curl down). If you wanted to do a fade in, you'd have to either dig down to CATransition's fade transition, or set up an explicit animation of your UIView's alpha.

Note that CATransition on Mac OS X will let you specify an arbitrary CoreImage filter to use as a transition, but as it stands now you can't do this on the iPhone, which lacks CoreImage.

How to load local html file into UIWebView

by this you can load html file which is in your project Assets(bundle) to webView.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

may be this is useful to you.

EXEC sp_executesql with multiple parameters

Here is a simple example:

EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;

Your call will be something like this

EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID

Difference between ref and out parameters in .NET

Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.

Move layouts up when soft keyboard is shown?

I have found a solution to my problems that it's pretty same as yours.

First of all, I only have a LinearLayout with 2 elements, an ImageView and a LinearLayout wich contains 2 EditText and one Button, so I needed to keep them separate in full screen without keyboard, and when the keyboard appears they should look closer.

So I added the view between them with the height attribute in 0dp and weight 1, that let me keep my views separate one form each other. and when the keyboard appers, as they don't have a fix height, they just resize and keep the aspect.

Voila! The layout resize and the distance between my views is the same when the keyboard is or not present.

Visual C++: How to disable specific linker warnings?

EDIT: don't use vc80 / Visual Studio 2005, but Visual Studio 2008 / vc90 versions of the CGAL library (maybe from here).

Linker Tools Warning LNK4099:

You could also compile with /Z7, so the pdb doesn't need to be used, or remove the /DEBUG linker option if you do not have .pdb files for the objects you are linking.

How can I use external JARs in an Android project?

If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):

  1. Select the Project view in the Project sideview (instead of Packages or Android)
  2. Create a folder called libs in your project's root folder
  3. Copy your JAR files to the libs folder
  4. The sideview will be updated and the JAR files will show up in your project
  5. Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
  6. After that, all you need to do is reference the new classes in your code, eg. import javax.mail.*

How to repeat last command in python interpreter shell?

In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys.

Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

Assign null to a SqlParameter

My code, working in real project Look the ternary operator beafore make the sqlparameter this is the best way for me, withou problems:

    public bool Key_AddExisting
    (
          string clave
        , int? idHito_FileServer
        , int? idTipoDocumental_Almacen
        , string tipoExp_CHJ
        , int idTipoExp_Verti2
        , int idMov_Verti2
    )
    {
        List<SqlParameter> pars = new List<SqlParameter>()
        {
              new SqlParameter { ParameterName = "@Clave", Value = clave }
    LOOK -> , idHito_FileServer == null ? new SqlParameter { ParameterName = "@IdHito_FileServer", Value = DBNull.Value } : new SqlParameter { ParameterName = "@IdHito_FileServer", Value = idHito_FileServer }
    LOOK -> , idTipoDocumental_Almacen == null ? new SqlParameter { ParameterName = "@IdTipoDocumental_Almacen", Value = DBNull.Value } : new SqlParameter { ParameterName = "@IdTipoDocumental_Almacen", Value = idTipoDocumental_Almacen }
            , new SqlParameter { ParameterName = "@TipoExp_CHJ", Value = tipoExp_CHJ }
            , new SqlParameter { ParameterName = "@IdTipoExp_Verti2", Value = idTipoExp_Verti2 }
            , new SqlParameter { ParameterName = "@IdMov_Verti2", Value = idMov_Verti2 }
        };

        string sql = "INSERT INTO [dbo].[Enlaces_ClavesCHJ_MovimientosVerti2] " +
            "( " +
            "  [Clave] " +
            ", [IdHito_FileServer] " +
            ", [IdTipoDocumental_Almacen] " +
            ", [TipoExp_CHJ] " +
            ", [IdTipoExp_Verti2] " +
            ", [IdMov_Verti2] " +
            ") " +
            "VALUES" +
            "( " +
            "  @Clave" +
            ", @IdHito_FileServer" +
            ", @IdTipoDocumental_Almacen" +
            ", @TipoExp_CHJ" +
            ", @IdTipoExp_Verti2" +
            ", @IdMov_Verti2" +
            ")";

        return DbBasic.ExecNonQuery(ref this.conn, sql, pars);
    }

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

XAMPP Apache won't start

I reinstalled it in another drive and that fixed it. But I have no idea what caused the problem in the first place.

How to round to 2 decimals with Python?

Most answers suggested round or format. round sometimes rounds up, and in my case I needed the value of my variable to be rounded down and not just displayed as such.

round(2.357, 2)  # -> 2.36

I found the answer here: How do I round a floating point number up to a certain decimal place?

import math
v = 2.357
print(math.ceil(v*100)/100)  # -> 2.36
print(math.floor(v*100)/100)  # -> 2.35

or:

from math import floor, ceil

def roundDown(n, d=8):
    d = int('1' + ('0' * d))
    return floor(n * d) / d

def roundUp(n, d=8):
    d = int('1' + ('0' * d))
    return ceil(n * d) / d

Calling C++ class methods via a function pointer

I came here to learn how to create a function pointer (not a method pointer) from a method but none of the answers here provide a solution. Here is what I came up with:

template <class T> struct MethodHelper;
template <class C, class Ret, class... Args> struct MethodHelper<Ret (C::*)(Args...)> {
    using T = Ret (C::*)(Args...);
    template <T m> static Ret call(C* object, Args... args) {
        return (object->*m)(args...);
    }
};

#define METHOD_FP(m) MethodHelper<decltype(m)>::call<m>

So for your example you would now do:

Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = METHOD_FP(&Dog::bark);
(*bark)(&dog); // or simply bark(&dog)

Edit:
Using C++17, there is an even better solution:

template <auto m> struct MethodHelper;
template <class C, class Ret, class... Args, Ret (C::*m)(Args...)> struct MethodHelper<m> {
    static Ret call(C* object, Args... args) {
        return (object->*m)(args...);
    }
};

which can be used directly without the macro:

Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = MethodHelper<&Dog::bark>::call;
(*bark)(&dog); // or simply bark(&dog)

For methods with modifiers like const you might need some more specializations like:

template <class C, class Ret, class... Args, Ret (C::*m)(Args...) const> struct MethodHelper<m> {
    static Ret call(const C* object, Args... args) {
        return (object->*m)(args...);
    }
};

How do you disable viewport zooming on Mobile Safari?

I got it working in iOS 12 with the following code:

if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
  window.document.addEventListener('touchmove', e => {
    if(e.scale !== 1) {
      e.preventDefault();
    }
  }, {passive: false});
}

With the first if statement I ensure it will only execute in iOS environments (if it executes in Android the scroll behivour will get broken). Also, note the passive option set to false.

How to stop (and restart) the Rails Server?

Now in rails 5 yu can do:

rails restart

This print by rails --tasks

Restart app by touching tmp/restart.txt

I think that is usefully if you run rails as a demon

Spring Boot: How can I set the logging level with application.properties?

Making sure Dave Syer tip gets some love, because adding debug=true to application.properties will indeed enable debug logging.

How can I selectively escape percent (%) in Python strings?

If you are using Python 3.6 or newer, you can use f-string:

>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.

Android WebView style background-color:transparent ignored on android 2.2

  • After trying everything given above. I found it doesn't matter either you specify
    webView.setBackgroundColor(Color.TRANSPARENT) before or after loadUrl() /loadData().
  • The thing that matters is you should explicitly declare android:hardwareAccelerated="false" in the manifest.

Tested on IceCream Sandwich

Converting camel case to underscore case in ruby

Here's how Rails does it:

   def underscore(camel_cased_word)
     camel_cased_word.to_s.gsub(/::/, '/').
       gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
       gsub(/([a-z\d])([A-Z])/,'\1_\2').
       tr("-", "_").
       downcase
   end

Pretty-print a Map in Java

Or put your logic into a tidy little class.

public class PrettyPrintingMap<K, V> {
    private Map<K, V> map;

    public PrettyPrintingMap(Map<K, V> map) {
        this.map = map;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<Entry<K, V>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<K, V> entry = iter.next();
            sb.append(entry.getKey());
            sb.append('=').append('"');
            sb.append(entry.getValue());
            sb.append('"');
            if (iter.hasNext()) {
                sb.append(',').append(' ');
            }
        }
        return sb.toString();

    }
}

Usage:

Map<String, String> myMap = new HashMap<String, String>();

System.out.println(new PrettyPrintingMap<String, String>(myMap));

Note: You can also put that logic into a utility method.

Bootstrap 3 Collapse show state with Chevron icon

Here's a couple of pure css helper classes which lets you handle any kind of toggle content right in your html.

It works with any element you need to switch. Whatever your layout is you just put it inside a couple of elements with the .if-collapsed and .if-not-collapsed classes within the toggle element.

The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.

It also requires the :not selector, it doesn't work on IE8.

HTML example:

<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
  <!--You can put any valid html inside these!-->
  <span class="if-collapsed">Open</span>
  <span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>

Less version:

[data-toggle="collapse"] {
    &.collapsed .if-not-collapsed {
         display: none;
    }
    &:not(.collapsed) .if-collapsed {
         display: none;
    }
}

CSS version:

[data-toggle="collapse"].collapsed .if-not-collapsed {
  display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
  display: none;
}

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.

Next:

s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

How to implement HorizontalScrollView like Gallery?

I have created a horizontal ListView in every row of ListView if you want single You can do the following

Here I am just creating horizontalListView of Thumbnail of Videos Like this

enter image description here

The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView

Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child

Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
    for (int index = 0; index < mImageCursor.getCount(); index++) {
        mImageCursor.moveToPosition(index);
        ImageView iv = (ImageView) imageViewInfalter.inflate(
            R.layout.image_view, null);
                    name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoDefaultName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
                    if (logoFile.exists()) {    
                Uri uri = Uri.fromFile(logoFile);
                iv.setImageURI(uri);                    
            }
            iv.setScaleType(ScaleType.FIT_XY);
            mVideosThumbs.addView(iv);
    }
    mImageCursor.close();
    mImageCursor = null;
    } else {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
                    R.layout.image_view, null);
        String name = "";
        File logoFile;
        name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoMediumName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
        if (logoFile.exists()) {
            Uri uri = Uri.fromFile(logoFile);
            iv.setImageURI(uri);
            }
        }

My xml for HorizontalListView

<HorizontalScrollView
    android:id="@+id/horizontalScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/linearLayoutTitle"
    android:background="@drawable/shelf"
    android:paddingBottom="@dimen/Playlist_TopBottom_margin"
    android:paddingLeft="@dimen/playlist_RightLeft_margin"
    android:paddingRight="@dimen/playlist_RightLeft_margin"
    android:paddingTop="@dimen/Playlist_TopBottom_margin" >

    <LinearLayout
        android:id="@+id/linearLayoutVideos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>

and Also my Image View as each child

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"


  android:id="@+id/imageViewThumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginRight="20dp"
    android:adjustViewBounds="true"
    android:background="@android:color/transparent"
    android:contentDescription="@string/action_settings"
    android:cropToPadding="true"
    android:maxHeight="200dp"
    android:maxWidth="240dp"
    android:padding="@dimen/playlist_image_padding"
    android:scaleType="centerCrop"
    android:src="@drawable/loading" />

To learn More you can follow the following links which have some easy samples

  1. http://www.dev-smart.com/?p=34
  2. Horizontal ListView in Android?

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How can I check if the array of objects have duplicate property values?

In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.

_x000D_
_x000D_
const values = [_x000D_
  { name: 'someName1' },_x000D_
  { name: 'someName2' },_x000D_
  { name: 'someName3' },_x000D_
  { name: 'someName1' }_x000D_
]_x000D_
_x000D_
const uniqueValues = new Set(values.map(v => v.name));_x000D_
_x000D_
if (uniqueValues.size < values.length) {_x000D_
  console.log('duplicates found')_x000D_
}
_x000D_
_x000D_
_x000D_

Sort columns of a dataframe by column name

If you only want one or more columns in the front and don't care about the order of the rest:

require(dplyr)
test %>%
  select(B, everything())

jquery count li elements inside ul -> length?

Working jsFiddle

Please use .size() function instead of .length and also specify li tag in selector.

Change your code like.

if ( $('#menu ul li').size() > 1 ) {

Automatically set appsettings.json for dev and release environments in asp.net core?

This is version that works for me when using a console app without a web page:

var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true);

            IConfigurationRoot configuration = builder.Build();
            AppSettings appSettings = new AppSettings();
            configuration.GetSection("AppSettings").Bind(appSettings);

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

git: How to diff changed files versus previous versions after a pull?

There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse for more details. In this case, you probably want:

git diff HEAD@{1}

The @{1} means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.

I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do

git diff HEAD@{1} filename

This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

For me, I have to disconnect (change workgroup/domain) from the Domain and reconnect.

C# - Making a Process.Start wait until the process has start-up

To extend @ChrisG's idea, a little, consider using process.MainWindowHandle and seeing if the window message loop is responding. Use p/invoke this Win32 api: SendMessageTimeout. From that link:

If the function succeeds, the return value is nonzero. SendMessageTimeout does not provide information about individual windows timing out if HWND_BROADCAST is used.

If the function fails or times out, the return value is 0. To get extended error information, call GetLastError. If GetLastError returns ERROR_TIMEOUT, then the function timed out.

Java Returning method which returns arraylist?

Your method can be called and the arraylist can be stored like this

YourClassName class = new YourClassName();
Arraylist<Integer> numbers = class.numbers(); 

This also allows the arraylist to be manipulated further in this class

Convert seconds value to hours minutes seconds?

Here's my function to address the problem:

public static String getConvertedTime(double time){

    double h,m,s,mil;

    mil = time % 1000;
    s = time/1000;
    m = s/60;
    h = m/60;
    s = s % 60;
    m = m % 60;
    h = h % 24;

    return ((int)h < 10 ? "0"+String.valueOf((int)h) : String.valueOf((int)h))+":"+((int)m < 10 ? "0"+String.valueOf((int)m) : String.valueOf((int)m))
            +":"+((int)s < 10 ? "0"+String.valueOf((int)s) : String.valueOf((int)s))
            +":"+((int)mil > 100 ? String.valueOf((int)mil) : (int)mil > 9 ? "0"+String.valueOf((int)mil) : "00"+String.valueOf((int)mil));
}

How can I refresh c# dataGridView after update ?

You can use SqlDataAdapter to update the DataGridView

     using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Table", conn))
            {
               DataTable dt = new DataTable();
                 ad.Fill(dt);
               dataGridView1.DataSource = dt;
            }
        }

Get element by id - Angular2

Complate Angular Way ( Set/Get value by Id ):

// In Html tag

 <button (click) ="setValue()">Set Value</button>
 <input type="text"  #userNameId />

// In component .ts File

    export class testUserClass {
       @ViewChild('userNameId') userNameId: ElementRef;

      ngAfterViewInit(){
         console.log(this.userNameId.nativeElement.value );
       }

      setValue(){
        this.userNameId.nativeElement.value = "Sample user Name";
      }



   }

Can anyone explain IEnumerable and IEnumerator to me?

IEnumerable is a box that contains Ienumerator. IEnumerable is base interface for all the collections. foreach loop can operate if the collection implements IEnumerable. In the below code it explains the step of having our own Enumerator. Lets first define our Class of which we are going to make the collection.

public class Customer
{
    public String Name { get; set; }
    public String City { get; set; }
    public long Mobile { get; set; }
    public double Amount { get; set; }
}

Now we will define the Class which will act as a collection for our class Customer. Notice that it is implementing the interface IEnumerable. So that we have to implement the method GetEnumerator. This will return our custom Enumerator.

public class CustomerList : IEnumerable
{
    Customer[] customers = new Customer[4];
    public CustomerList()
    {
        customers[0] = new Customer { Name = "Bijay Thapa", City = "LA", Mobile = 9841639665, Amount = 89.45 };
        customers[1] = new Customer { Name = "Jack", City = "NYC", Mobile = 9175869002, Amount = 426.00 };
        customers[2] = new Customer { Name = "Anil min", City = "Kathmandu", Mobile = 9173694005, Amount = 5896.20 };
        customers[3] = new Customer { Name = "Jim sin", City = "Delhi", Mobile = 64214556002, Amount = 596.20 };
    }

    public int Count()
    {
        return customers.Count();
    }
    public Customer this[int index]
    {
        get
        {
            return customers[index];
        }
    }
    public IEnumerator GetEnumerator()
    {
        return customers.GetEnumerator(); // we can do this but we are going to make our own Enumerator
        return new CustomerEnumerator(this);
    }
}

Now we are going to create our own custom Enumerator as follow. So, we have to implement method MoveNext.

 public class CustomerEnumerator : IEnumerator
    {
        CustomerList coll;
        Customer CurrentCustomer;
        int currentIndex;
        public CustomerEnumerator(CustomerList customerList)
        {
            coll = customerList;
            currentIndex = -1;
        }

        public object Current => CurrentCustomer;

        public bool MoveNext()
        {
            if ((currentIndex++) >= coll.Count() - 1)
                return false;
            else
                CurrentCustomer = coll[currentIndex];
            return true;
        }

        public void Reset()
        {
            // we dont have to implement this method.
        }
    }

Now we can use foreach loop over our collection like below;

    class EnumeratorExample
    {
        static void Main(String[] args)
        {

            CustomerList custList = new CustomerList();
            foreach (Customer cust in custList)
            {
                Console.WriteLine("Customer Name:"+cust.Name + " City Name:" + cust.City + " Mobile Number:" + cust.Amount);
            }
            Console.Read();

        }
    }

Select All distinct values in a column using LINQ

var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

Substring a string from the end of the string

C# 8 introduced indices and ranges which allow you to write

str[^2..]

This is equivalent to

str.Substring(str.Length - 2, str.Length)

In fact, this is almost exactly what the compiler will generate, so there's no overhead.

Note that you will get an ArgumentOutOfRangeException if the range isn't within the string.

How to pass variables from one php page to another without form?

check to make sure the variable is set. Then clean it before using it:

isset($_GET['var'])?$var=mysql_escape_string($_GET['var']):$var='SomeDefaualtValue';

Otherwise, assign it a default value ($var='' is fine) to avoid the error you mentioned.

Why shouldn't I use mysql_* functions in PHP?

This answer is written to show just how trivial it is to bypass poorly written PHP user-validation code, how (and using what) these attacks work and how to replace the old MySQL functions with a secure prepared statement - and basically, why StackOverflow users (probably with a lot of rep) are barking at new users asking questions to improve their code.

First off, please feel free to create this test mysql database (I have called mine prep):

mysql> create table users(
    -> id int(2) primary key auto_increment,
    -> userid tinytext,
    -> pass tinytext);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into users values(null, 'Fluffeh', 'mypass');
Query OK, 1 row affected (0.04 sec)

mysql> create user 'prepared'@'localhost' identified by 'example';
Query OK, 0 rows affected (0.01 sec)

mysql> grant all privileges on prep.* to 'prepared'@'localhost' with grant option;
Query OK, 0 rows affected (0.00 sec)

With that done, we can move to our PHP code.

Lets assume the following script is the verification process for an admin on a website (simplified but working if you copy and use it for testing):

<?php 

    if(!empty($_POST['user']))
    {
        $user=$_POST['user'];
    }   
    else
    {
        $user='bob';
    }
    if(!empty($_POST['pass']))
    {
        $pass=$_POST['pass'];
    }
    else
    {
        $pass='bob';
    }

    $database='prep';
    $link=mysql_connect('localhost', 'prepared', 'example');
    mysql_select_db($database) or die( "Unable to select database");

    $sql="select id, userid, pass from users where userid='$user' and pass='$pass'";
    //echo $sql."<br><br>";
    $result=mysql_query($sql);
    $isAdmin=false;
    while ($row = mysql_fetch_assoc($result)) {
        echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
        $isAdmin=true;
        // We have correctly matched the Username and Password
        // Lets give this person full access
    }
    if($isAdmin)
    {
        echo "The check passed. We have a verified admin!<br>";
    }
    else
    {
        echo "You could not be verified. Please try again...<br>";
    }
    mysql_close($link);

?>

<form name="exploited" method='post'>
    User: <input type='text' name='user'><br>
    Pass: <input type='text' name='pass'><br>
    <input type='submit'>
</form>

Seems legit enough at first glance.

The user has to enter a login and password, right?

Brilliant, not enter in the following:

user: bob
pass: somePass

and submit it.

The output is as follows:

You could not be verified. Please try again...

Super! Working as expected, now lets try the actual username and password:

user: Fluffeh
pass: mypass

Amazing! Hi-fives all round, the code correctly verified an admin. It's perfect!

Well, not really. Lets say the user is a clever little person. Lets say the person is me.

Enter in the following:

user: bob
pass: n' or 1=1 or 'm=m

And the output is:

The check passed. We have a verified admin!

Congrats, you just allowed me to enter your super-protected admins only section with me entering a false username and a false password. Seriously, if you don't believe me, create the database with the code I provided, and run this PHP code - which at glance REALLY does seem to verify the username and password rather nicely.

So, in answer, THAT IS WHY YOU ARE BEING YELLED AT.

So, lets have a look at what went wrong, and why I just got into your super-admin-only-bat-cave. I took a guess and assumed that you weren't being careful with your inputs and simply passed them to the database directly. I constructed the input in a way tht would CHANGE the query that you were actually running. So, what was it supposed to be, and what did it end up being?

select id, userid, pass from users where userid='$user' and pass='$pass'

That's the query, but when we replace the variables with the actual inputs that we used, we get the following:

select id, userid, pass from users where userid='bob' and pass='n' or 1=1 or 'm=m'

See how I constructed my "password" so that it would first close the single quote around the password, then introduce a completely new comparison? Then just for safety, I added another "string" so that the single quote would get closed as expected in the code we originally had.

However, this isn't about folks yelling at you now, this is about showing you how to make your code more secure.

Okay, so what went wrong, and how can we fix it?

This is a classic SQL injection attack. One of the simplest for that matter. On the scale of attack vectors, this is a toddler attacking a tank - and winning.

So, how do we protect your sacred admin section and make it nice and secure? The first thing to do will be to stop using those really old and deprecated mysql_* functions. I know, you followed a tutorial you found online and it works, but it's old, it's outdated and in the space of a few minutes, I have just broken past it without so much as breaking a sweat.

Now, you have the better options of using mysqli_ or PDO. I am personally a big fan of PDO, so I will be using PDO in the rest of this answer. There are pro's and con's, but personally I find that the pro's far outweigh the con's. It's portable across multiple database engines - whether you are using MySQL or Oracle or just about bloody anything - just by changing the connection string, it has all the fancy features we want to use and it is nice and clean. I like clean.

Now, lets have a look at that code again, this time written using a PDO object:

<?php 

    if(!empty($_POST['user']))
    {
        $user=$_POST['user'];
    }   
    else
    {
        $user='bob';
    }
    if(!empty($_POST['pass']))
    {
        $pass=$_POST['pass'];
    }
    else
    {
        $pass='bob';
    }
    $isAdmin=false;

    $database='prep';
    $pdo=new PDO ('mysql:host=localhost;dbname=prep', 'prepared', 'example');
    $sql="select id, userid, pass from users where userid=:user and pass=:password";
    $myPDO = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    if($myPDO->execute(array(':user' => $user, ':password' => $pass)))
    {
        while($row=$myPDO->fetch(PDO::FETCH_ASSOC))
        {
            echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
            $isAdmin=true;
            // We have correctly matched the Username and Password
            // Lets give this person full access
        }
    }

    if($isAdmin)
    {
        echo "The check passed. We have a verified admin!<br>";
    }
    else
    {
        echo "You could not be verified. Please try again...<br>";
    }

?>

<form name="exploited" method='post'>
    User: <input type='text' name='user'><br>
    Pass: <input type='text' name='pass'><br>
    <input type='submit'>
</form>

The major differences are that there are no more mysql_* functions. It's all done via a PDO object, secondly, it is using a prepared statement. Now, what's a prepred statement you ask? It's a way to tell the database ahead of running a query, what the query is that we are going to run. In this case, we tell the database: "Hi, I am going to run a select statement wanting id, userid and pass from the table users where the userid is a variable and the pass is also a variable.".

Then, in the execute statement, we pass the database an array with all the variables that it now expects.

The results are fantastic. Lets try those username and password combinations from before again:

user: bob
pass: somePass

User wasn't verified. Awesome.

How about:

user: Fluffeh
pass: mypass

Oh, I just got a little excited, it worked: The check passed. We have a verified admin!

Now, lets try the data that a clever chap would enter to try to get past our little verification system:

user: bob
pass: n' or 1=1 or 'm=m

This time, we get the following:

You could not be verified. Please try again...

This is why you are being yelled at when posting questions - it's because people can see that your code can be bypassed wihout even trying. Please, do use this question and answer to improve your code, to make it more secure and to use functions that are current.

Lastly, this isn't to say that this is PERFECT code. There are many more things that you could do to improve it, use hashed passwords for example, ensure that when you store sensetive information in the database, you don't store it in plain text, have multiple levels of verification - but really, if you just change your old injection prone code to this, you will be WELL along the way to writing good code - and the fact that you have gotten this far and are still reading gives me a sense of hope that you will not only implement this type of code when writing your websites and applications, but that you might go out and research those other things I just mentioned - and more. Write the best code you can, not the most basic code that barely functions.

How to change Android usb connect mode to charge only?

I have been searching for this for ages on my CM 11 android phone, running kitkat.

Well.. finally I found it. It's hidden in a totally unintuitive location:

  1. Go to settings
  2. Go to storage
  3. Open the menu and choose USB computer connection

Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.

Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).

jquery-ui-dialog - How to hook into dialog close event

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

Java: Clear the console

If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.

Something like the following code worked for me:

import jline.console.ConsoleReader;

public class JLineTest
{
    public static void main(String... args)
    throws Exception
    {
        ConsoleReader r = new ConsoleReader();

        while (true)
        {
            r.println("Good morning");
            r.flush();

            String input = r.readLine("prompt>");

            if ("clear".equals(input))
                r.clearScreen();
            else if ("exit".equals(input))
                return;
            else
                System.out.println("You typed '" + input + "'.");

        }
    }
}

When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.

Is it possible to apply CSS to half of a character?

Just for the record in history!

I've come up with a solution for my own work from 5-6 years ago, which is Gradext ( pure javascript and pure css, no dependency ) .

The technical explanation is you can create an element like this:

<span>A</span>

now if you want to make a gradient on text, you need to create some multiple layers, each individually specifically colored and the spectrum created will illustrate the gradient effect.

for example look at this is the word lorem inside of a <span> and will cause a horizontal gradient effect ( check the examples ):

 <span data-i="0" style="color: rgb(153, 51, 34);">L</span>
 <span data-i="1" style="color: rgb(154, 52, 35);">o</span>
 <span data-i="2" style="color: rgb(155, 53, 36);">r</span>
 <span data-i="3" style="color: rgb(156, 55, 38);">e</span>
 <span data-i="4" style="color: rgb(157, 56, 39);">m</span>

and you can continue doing this pattern for a long time and long paragraph as well.

enter image description here

But!

What if you want to create a vertical gradient effect on texts?

Then there's another solution which could be helpful. I will describe in details.

Assuming our first <span> again. but the content shouldn't be the letters individually; the content should be the whole text, and now we're going to copy the same ??<span> again and again ( count of spans will define the quality of your gradient, more span, better result, but poor performance ). have a look at this:

<span data-i="6" style="color: rgb(81, 165, 39); overflow: hidden; height: 11.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="7" style="color: rgb(89, 174, 48); overflow: hidden; height: 12.8px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="8" style="color: rgb(97, 183, 58); overflow: hidden; height: 14.4px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="9" style="color: rgb(105, 192, 68); overflow: hidden; height: 16px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="10" style="color: rgb(113, 201, 78); overflow: hidden; height: 17.6px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="11" style="color: rgb(121, 210, 88); overflow: hidden; height: 19.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>

enter image description here

Again, But!

what if you want to make these gradient effects to move and create an animation out of it?

well, there's another solution for it too. You should definitely check animation: true or even .hoverable() method which will lead to a gradient to start based on cursor position! ( sounds cool xD )

enter image description here

this is simply how we're creating gradients ( linear or radial ) on texts. If you liked the idea or want to know more about it, you should check the links provided.


Maybe this is not the best option, maybe not the best performant way to do this, but it will open up some space to create exciting and delightful animations to inspire some other people for a better solution.

It will allow you to use gradient style on texts, which is supported by even IE8!

Here you can find a working live demo and the original repository is here on GitHub as well, open source and ready to get some updates ( :D )

This is my first time ( yeah, after 5 years, you've heard it right ) to mention this repository anywhere on the Internet, and I'm excited about that!


[Update - 2019 August:] Github removed github-pages demo of that repository because I'm from Iran! Only the source code is available here tho...

How to get the request parameters in Symfony 2?

If you need getting the value from a select, you can use:

$form->get('nameSelect')->getClientData();

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Sequelize.js delete query?

Don't know if the question is still relevant but I have found the following on Sequelize's documentation.

User.destroy('`name` LIKE "J%"').success(function() {
    // We just deleted all rows that have a name starting with "J"
})

http://sequelizejs.com/blog/state-of-v1-7-0

Hope it helps!

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Indexes of all occurrences of character in a string

With Java9, one can make use of the iterate(int seed, IntPredicate hasNext,IntUnaryOperator next) as follows:-

List<Integer> indexes = IntStream
          .iterate(word.indexOf(c), index -> index >= 0, index -> word.indexOf(c, index + 1))
          .boxed()
          .collect(Collectors.toList());
System.out.printlnt(indexes);

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

How to check if one DateTime is greater than the other in C#

You can use the overloaded < or > operators.

For example:

DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

C# Test if user has write access to a folder

You have a potential race condition in your code--what happens if the user has permissions to write to the folder when you check, but before the user actually writes to the folder this permission is withdrawn? The write will throw an exception which you will need to catch and handle. So the initial check is pointless. You might as well just do the write and handle any exceptions. This is the standard pattern for your situation.

Pandas conditional creation of a series/dataframe column

If you only have two choices to select from:

df['color'] = np.where(df['Set']=='Z', 'green', 'red')

For example,

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)

yields

  Set Type  color
0   Z    A  green
1   Z    B  green
2   X    B    red
3   Y    C    red

If you have more than two conditions then use np.select. For example, if you want color to be

  • yellow when (df['Set'] == 'Z') & (df['Type'] == 'A')
  • otherwise blue when (df['Set'] == 'Z') & (df['Type'] == 'B')
  • otherwise purple when (df['Type'] == 'B')
  • otherwise black,

then use

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
conditions = [
    (df['Set'] == 'Z') & (df['Type'] == 'A'),
    (df['Set'] == 'Z') & (df['Type'] == 'B'),
    (df['Type'] == 'B')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)

which yields

  Set Type   color
0   Z    A  yellow
1   Z    B    blue
2   X    B  purple
3   Y    C   black

How to get UTC+0 date in Java 8?

tl;dr

Instant.now()

java.time

The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Instant instant = Instant.now();

The toString method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.

String output = instant.toString();  

2016-06-27T19:15:25.864Z

The Instant class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.

OffsetDateTime

But Instant has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant to OffsetDateTime. Specify an offset-from-UTC. In java.time that means a ZoneOffset object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

2016-06-27T19:15:25.864Z

Or skip the Instant class.

OffsetDateTime.now( ZoneOffset.UTC )

Now with an OffsetDateTime object in hand, you can use DateTimeFormatter to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter.

ZonedDateTime

When you want to display wall-clock time for some particular time zone, apply a ZoneId to get a ZonedDateTime.

In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00. So note how the time-of-day is four hours earlier in the output, 15 instead of 19 hours. Instant and the ZonedDateTime both represent the very same simultaneous moment, just viewed through two different lenses.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

2016-06-27T15:15:25.864-04:00[America/Montreal]

Converting

While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant ) and java.util.Date::toInstant.

java.util.Date utilDate = java.util.Date.from( instant );

And going the other direction.

Instant instant= utilDate.toInstant();

Similarly, look for new methods added to GregorianCalendar (subclass of Calendar) to convert to and from java.time.ZonedDateTime.

Table of types of date-time classes in modern java.time versus legacy.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo.

declare @n char(1)
set @n = char(10)

declare @stmt nvarchar(max)

-- procedures
select @stmt = isnull( @stmt + @n, '' ) +
    'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures


-- check constraints
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + ']    drop constraint [' + name + ']'
from sys.check_constraints

-- functions
select @stmt = isnull( @stmt + @n, '' ) +
    'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )

-- views
select @stmt = isnull( @stmt + @n, '' ) +
    'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views

-- foreign keys
select @stmt = isnull( @stmt + @n, '' ) +
    'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys

-- tables
select @stmt = isnull( @stmt + @n, '' ) +
    'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables

-- user defined types
select @stmt = isnull( @stmt + @n, '' ) +
    'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1


exec sp_executesql @stmt

Source: an Adam Anderson blog post

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

How to load a tsv file into a Pandas DataFrame?

data = pd.read_csv('your_dataset.tsv', delimiter = '\t', quoting = 3)

You can use a delimiter to separate data, quoting = 3 helps to clear quotes in datasst

JavaScript array to CSV

The following code were written in ES6 and it will work in most of the browsers without an issue.

_x000D_
_x000D_
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
_x000D_
_x000D_

Custom Drawable for ProgressBar/ProgressDialog

Try setting:

android:indeterminateDrawable="@drawable/progress" 

It worked for me. Here is also the code for progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#4c737373"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate> 

Launch programs whose path contains spaces

Copy the folder, firefox.exe is in and place in the c:\ only. The script is having a hard time climbing your file tree. I found that when I placed the *.exe file in the c:\ it eliminated the error message " file not found."

Async await in linq select

I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:

public static class IEnumerableExtensions {
    public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
        foreach (var item in source) {
            yield return await selector(item);
        }
    }
}

public static class IAsyncEnumerableExtensions {
    public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
        var list = new List<TSource>();

        await foreach (var item in source) {
            list.Add(item);
        }

        return list;
    }
}

This can be consumed by saying:

var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();

Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:

var inputs = await events
    .ToAsyncEnumerable()
    .SelectAwait(async ev => await ProcessEventAsync(ev))
    .ToListAsync();

How to make a website secured with https

@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.

If you're using Forms Authentication and standard controls like <asp:Login> there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.

In web.config, under the <system.web> section you'll need to disable anonymous access by default:

<authorization>
 <deny users="?" />
</authorization>

Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location> element and must be located at the <configuration> level (outside the <system.web> section), like this:

<!-- Anonymous files -->
<location path="Login.aspx">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:

<!-- Anonymous folders -->
<location path="styles">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Be aware that the location's path attribute is relative to the web.config folder and cannot have a ~/ prefix, unlike most other path-type configuration attributes.

How do I convert a org.w3c.dom.Document object to a String?

This worked for me, as documented on this page:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();

How do I display images from Google Drive on a website?

Google Drive Hosting is now deprecated. It stopped working from August 31, 2016.

hosting on Google Drive - deprecation schedule

I have removed the explanation of how to previously host an image on Google Drive.

How to show math equations in general github's markdown(not github's blog)

Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image. https://www.mathcha.io/

How to increment a variable on a for loop in jinja template?

Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here.

{% for item in item_list %}
    {{ forloop.counter }} {# starting index 1 #}
    {{ forloop.counter0 }} {# starting index 0 #}

    {# do your stuff #}
{% endfor %}

Read more here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

How to display loading image while actual image is downloading

Use a javascript constructor with a callback that fires when the image has finished loading in the background. Just used it and works great for me cross-browser. Here's the thread with the answer.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

Yea, Indeed @Evert answer is perfectly correct. In addition I'll like to add one more reason that could encounter such error.

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,200))])

This will be perfectly fine, However, This leads to error:

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,201))])

ValueError: could not broadcast input array from shape (20,200) into shape (20)

The numpy arry within the list, must also be the same size.

Angular - Can't make ng-repeat orderBy work

You're going to have to reformat your releases object to be an array of objects. Then you'll be able to sort them the way you're attempting.

Copy a git repo without history

Isn't this exactly what squashing a rebase does? Just squash everything except the last commit and then (force) push it.

Where is the itoa function in Linux?

You can use this program instead of sprintf.

void itochar(int x, char *buffer, int radix);

int main()
{
    char buffer[10];
    itochar(725, buffer, 10);
    printf ("\n %s \n", buffer);
    return 0;
}

void itochar(int x, char *buffer, int radix)
{
    int i = 0 , n,s;
    n = s;
    while (n > 0)
    {
        s = n%radix;
        n = n/radix;
        buffer[i++] = '0' + s;
    }
    buffer[i] = '\0';
    strrev(buffer);
}

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

mysqldump data only

Best to dump to a compressed file

mysqldump --no-create-info -u username -hhostname -p dbname | gzip > /backupsql.gz

and to restore using pv apt-get install pv to monitor progress

pv backupsql.gz | gunzip | mysql -uusername -hhostip -p dbname

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

How to create a label inside an <input> element?

In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.

It's easy to implement and degrades nicely for screen readers and users with no javascript.

Take a look at the two examples here: http://attardi.org/labels/

I usually use the second method (labels2) on my forms.

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Remove Primary Key in MySQL

One Line:

ALTER TABLE  `user_customer_permission` DROP PRIMARY KEY , ADD PRIMARY KEY (  `id` )

You will also not lose the auto-increment and have to re-add it which could have side-effects.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Xcode 7.2 no matching provisioning profiles found

Check your Keychain - look in Login and System keychains for expired certificates or error messages.

I found certs with "this certificate has an invalid user" error messages, and an expired Apple Worldwide Developer Relations Certificate.

Delete them and install the new AWDRC certificate from https://developer.apple.com/certificationauthority/AppleWWDRCA.cer

Then follow the accepted answer to get Xcode to use the new certificates.

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).

You want to deserialize into a single RootObject.

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

How to Get a Specific Column Value from a DataTable?

I suggest such way based on extension methods:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

System.Data.DataSetExtensions.dll needs to be referenced.

How do I align views at the bottom of the screen?

Creating both header and footer, here is an example:

Layout XML

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/backgroundcolor"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:background="#FF0000">
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:background="#FFFF00">
    </RelativeLayout>

</RelativeLayout>

Screenshot

Enter image description here

Find Nth occurrence of a character in a string

Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:

yourString.Where(c => c == 't').Count();

PostgreSQL database service

If you don't want or can't install postgres again, you can install the server from the binary zip like this post explains it.