Programs & Examples On #Browscap

How does one create an InputStream from a String?

InputStream in = new ByteArrayInputStream(yourstring.getBytes());

Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

How do I replace NA values with zeros in an R dataframe?

The cleaner package has an na_replace() generic, that at default replaces numeric values with zeroes, logicals with FALSE, dates with today, etc.:

starwars %>% na_replace()

It even supports vectorised replacements:

mtcars[1:6, c("mpg", "hp")] <- NA
na_replace(mtcars, mpg, hp, replacement = c(999, 123))


What is the difference between prefix and postfix operators?

There is a big difference between postfix and prefix versions of ++.

In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i.

In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i.

Let's analyze the following code line by line:

int i = 10;   // (1)
int j = ++i;  // (2)
int k = i++;  // (3)
  1. i is set to 10 (easy).
  2. Two things on this line:
    • i is incremented to 11.
    • The new value of i is copied into j. So j now equals 11.
  3. Two things on this line as well:
    • i is incremented to 12.
    • The original value of i (which is 11) is copied into k. So k now equals 11.

So after running the code, i will be 12 but both j and k will be 11.

The same stuff holds for postfix and prefix versions of --.

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

Java - ignore exception and continue

LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

About catching ANY exception

Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:

import traceback
import logging

except Exception as e:
    # Logs the error appropriately. 

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

CSS selector for first element with class

I think a lot of people have explained already. your code is selecting only first child of the first instance. If you want to select all the first children of red class, you need to use

.home > .red:first-child {
    /* put your styling here */

Refresh (reload) a page once using jQuery?

 - location = location
 - location = location.href
 - location = window.location
 - location = self.location
 - location = window.location.href
 - location = self.location.href
 - location = location['href']
 - location = window['location']
 - location = window['location'].href
 - location = window['location']['href']

You don't need jQuery for this. You can do it with JavaScript.

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
        return null;

Then when you click on the button -

enter image description here

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
# DropBox - syncd
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
# DropNot - NOT syncd !
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
# vim
alias v='vim'
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

How to resolve "must be an instance of string, string given" prior to PHP 7?

As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.

In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.

Always pass weak reference of self into block in ARC?

You don't have to always use a weak reference. If your block is not retained, but executed and then discarded, you can capture self strongly, as it will not create a retain cycle. In some cases, you even want the block to hold the self until the completion of the block so it does not deallocate prematurely. If, however, you capture the block strongly, and inside capture self, it will create a retain cycle.

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Reverse a changelist submission

You cannot undo a successful changelist submission, but you can reverse previously submitted changes in two ways:

Rollback restores a file or set of files back to a specified changelist, date or revision. Any changes made after that point in time are not retained. Back out removes specific changes made at a given changelist, date or revision but allows a user to keep changes made in subsequent revisions.

For details please refer to

CSS I want a div to be on top of everything

I gonna assumed you making a popup with code from WW3 school, correct? check it css. the .modal one, there're already word z-index there. just change from 1 to 100.

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */

Determining image file size + dimensions via Javascript?

var img = new Image();
img.src = sYourFilePath;
var iSize = img.fileSize;

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Perm gen space error occurs due to the use of large space rather then jvm provided space to executed the code.

The best solution for this problem in UNIX operating systems is to change some configuration on the bash file. The following steps solve the problem.

Run command gedit .bashrc on terminal.

Create JAVA_OTPS variable with following value:

export JAVA_OPTS="-XX:PermSize=256m -XX:MaxPermSize=512m"

Save the bash file. Run command exec bash on the terminal. Restart the server.

I hope this approach will work on your problem. If you use a Java version lower than 8 this issue occurs sometimes. But if you use Java 8 the problem never occurs.

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):


  • prepare web-page where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.


Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from because it has ADID which is on servers whitelist

Set width of a "Position: fixed" div relative to parent div

Use this CSS:

#container {
    width: 400px;
    border: 1px solid red;

#fixed {
    position: fixed;
    width: inherit;
    border: 1px solid green;

The #fixed element will inherit it's parent width, so it will be 100% of that.

How using try catch for exception handling is best practice

An exception is a blocking error.

First of all, the best practice should be don't throw exceptions for any kind of error, unless it's a blocking error.

If the error is blocking, then throw the exception. Once the exception is already thrown, there's no need to hide it because it's exceptional; let the user know about it (you should reformat the whole exception to something useful to the user in the UI).

Your job as software developer is to endeavour to prevent an exceptional case where some parameter or runtime situation may end in an exception. That is, exceptions mustn't be muted, but these must be avoided.

For example, if you know that some integer input could come with an invalid format, use int.TryParse instead of int.Parse. There is a lot of cases where you can do this instead of just saying "if it fails, simply throw an exception".

Throwing exceptions is expensive.

If, after all, an exception is thrown, instead of writing the exception to the log once it has been thrown, one of best practices is catching it in a first-chance exception handler. For example:

  • ASP.NET: Global.asax Application_Error
  • Others: AppDomain.FirstChanceException event.

My stance is that local try/catches are better suited for handling special cases where you may translate an exception into another, or when you want to "mute" it for a very, very, very, very, very special case (a library bug throwing an unrelated exception that you need to mute in order to workaround the whole bug).

For the rest of the cases:

  • Try to avoid exceptions.
  • If this isn't possible: first-chance exception handlers.
  • Or use a PostSharp aspect (AOP).

Answering to @thewhiteambit on some comment...

@thewhiteambit said:

Exceptions are not Fatal-Errors, they are Exceptions! Sometimes they are not even Errors, but to consider them Fatal-Errors is completely false understanding of what Exceptions are.

First of all, how an exception can't be even an error?

  • No database connection => exception.
  • Invalid string format to parse to some type => exception
  • Trying to parse JSON and while input isn't actually JSON => exception
  • Argument null while object was expected => exception
  • Some library has a bug => throws an unexpected exception
  • There's a socket connection and it gets disconnected. Then you try to send a message => exception
  • ...

We might list 1k cases of when an exception is thrown, and after all, any of the possible cases will be an error.

An exception is an error, because at the end of the day it is an object which collects diagnostic information -- it has a message and it happens when something goes wrong.

No one would throw an exception when there's no exceptional case. Exceptions should be blocking errors because once they're thrown, if you don't try to fall into the use try/catch and exceptions to implement control flow they mean your application/service will stop the operation that entered into an exceptional case.

Also, I suggest everyone to check the fail-fast paradigm published by Martin Fowler (and written by Jim Shore). This is how I always understood how to handle exceptions, even before I got to this document some time ago.

[...] consider them Fatal-Errors is completely false understanding of what exceptions are.

Usually exceptions cut some operation flow and they're handled to convert them to human-understandable errors. Thus, it seems like an exception actually is a better paradigm to handle error cases and work on them to avoid an application/service complete crash and notify the user/consumer that something went wrong.

More answers about @thewhiteambit concerns

For example in case of a missing Database-Connection the program could exceptionally continue with writing to a local file and send the changes to the Database once it is available again. Your invalid String-To-Number casting could be tried to parse again with language-local interpretation on Exception, like as you try default English language to Parse("1,5") fails and you try it with German interpretation again which is completely fine because we use comma instead of point as separator. You see these Exceptions must not even be blocking, they only need some Exception-handling.

  1. If your app might work offline without persisting data to database, you shouldn't use exceptions, as implementing control flow using try/catch is considered as an anti-pattern. Offline work is a possible use case, so you implement control flow to check if database is accessible or not, you don't wait until it's unreachable.

  2. The parsing thing is also an expected case (not EXCEPTIONAL CASE). If you expect this, you don't use exceptions to do control flow!. You get some metadata from the user to know what his/her culture is and you use formatters for this! .NET supports this and other environments too, and an exception because number formatting must be avoided if you expect a culture-specific usage of your application/service.

An unhandled Exception usually becomes an Error, but Exceptions itself are not

This article is just an opinion or a point of view of the author.

Since Wikipedia can be also just the opinion of articule author(s), I wouldn't say it's the dogma, but check what Coding by exception article says somewhere in some paragraph:

[...] Using these exceptions to handle specific errors that arise to continue the program is called coding by exception. This anti-pattern can quickly degrade software in performance and maintainability.

It also says somewhere:

Incorrect exception usage

Often coding by exception can lead to further issues in the software with incorrect exception usage. In addition to using exception handling for a unique problem, incorrect exception usage takes this further by executing code even after the exception is raised. This poor programming method resembles the goto method in many software languages but only occurs after a problem in the software is detected.

Honestly, I believe that software can't be developed don't taking use cases seriously. If you know that...

  • Your database can go offline...
  • Some file can be locked...
  • Some formatting might be not supported...
  • Some domain validation might fail...
  • Your app should work in offline mode...
  • whatever use case... won't use exceptions for that. You would support these use cases using regular control flow.

And if some unexpected use case isn't covered, your code will fail fast, because it'll throw an exception. Right, because an exception is an exceptional case.

In the other hand, and finally, sometimes you cover exceptional cases throwing expected exceptions, but you don't throw them to implement control flow. You do it because you want to notify upper layers that you don't support some use case or your code fails to work with some given arguments or environment data/properties.

How to get the values of a ConfigurationSection of type NameValueSectionHandler

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

public class NameValueCollectionConfigurationSection : ConfigurationSection
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
        foreach ( string key in this.ConfigurationCollection.AllKeys )
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];

The usage is straightforward:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));

Regular expression for letters, numbers and - _

This is the pattern you are looking for


What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:


{0,5} Means 0-5 characters

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

How to inherit constructors?

No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.

Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.

No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
map = new google.maps.Map(document.getElementById('map'), mapOptions);

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
  } else {
    alert('Geocode was not successful for the following reason: ' + status);

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">

Or refer to the documentation

Lock, mutex, semaphore... what's the difference?

My understanding is that a mutex is only for use within a single process, but across its many threads, whereas a semaphore may be used across multiple processes, and across their corresponding sets of threads.

Also, a mutex is binary (it's either locked or unlocked), whereas a semaphore has a notion of counting, or a queue of more than one lock and unlock requests.

Could someone verify my explanation? I'm speaking in the context of Linux, specifically Red Hat Enterprise Linux (RHEL) version 6, which uses kernel 2.6.32.

How do I get class name in PHP?

It sounds like you answered your own question. get_class will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class

Here is their example:


 class foo 
     function name()
         echo "My name is " , get_class($this) , "\n";

 // create an object
 $bar = new foo();

 // external call
 echo "Its name is " , get_class($bar) , "\n"; // It's name is foo

 // internal call
 $bar->name(); // My name is foo

To make it more like your example you could do something like:


 class MyClass
       public static function getClass()
            return get_class();

Now you can do:

 $className = MyClass::getClass();

This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.


class MyClass
    public static function getClass()
        return get_called_class();

    public static function getDefiningClass()
        return get_class();

class MyExtendedClass extends MyClass {}

$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'

How to resolve this System.IO.FileNotFoundException

Check all the references carefully

  • Version remains same on target machine and local machine
  • If assembly is referenced from GAC, ensure that proper version is loaded

For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

The SQL Server Maximums are disclosed (this is the 2008 version)

A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.

Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)

At 100k items, it took some time then dropped with:

Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.

So 30k is possible, but just because you can do it - does not mean you should :)

Edit : Continued due to additional question.

50k worked, but 60k dropped out, so somewhere in there on my test rig btw.

In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)

The shortest possible output from git log containing author and date

To show the commits I have staged that are ready to push I do

git log remotes/trunk~4..HEAD --pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s" --date=short | awk -F'\t' '{gsub(/[, ]/,"",$2);gsub(/HEAD/, "\033[1;36mH\033[00m",$2);gsub(/master/, "\033[1;32mm\033[00m",$2);gsub(/trunk/, "\033[1;31mt\033[00m",$2);print $1 "\t" gensub(/([\(\)])/, "\033[0;33m\\1\033[00m","g",$2) $3}' | less -eiFRXS

The output looks something like:

ef87da7 2013-01-17 haslers      (Hm)Fix NPE in Frobble
8f6d80f 2013-01-17 haslers      Refactor Frobble
815813b 2013-01-17 haslers      (t)Add Wibble to Frobble
3616373 2013-01-17 haslers      Add Foo to Frobble
3b5ccf0 2013-01-17 haslers      Add Bar to Frobble
a1db9ef 2013-01-17 haslers      Add Frobble Widget

Where the first column appears in yellow, and the 'H' 'm' and 't' in parentesis show the HEAD, master and trunk and appear in their usual "--decorate" colors

Here it is with line breaks so you can see what it's doing:

git log remotes/trunk~4..HEAD --date=short
    --pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s"
    | awk -F'\t' '{
         gsub(/[, ]/,"",$2);
         gsub(/HEAD/, "\033[1;36mH\033[00m",$2);
         gsub(/master/, "\033[1;32mm\033[00m",$2);
         gsub(/trunk/, "\033[1;31mt\033[00m",$2);
         print $1 "\t" gensub(/([\(\)])/, "\033[0;33m\\1\033[00m","g",$2) $3}'

I have aliased to "staged" with:

git config alias.staged '!git log remotes/trunk~4..HEAD --date=short --pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s" | awk -F"\t" "{gsub(/[, ]/,\"\",\$2);gsub(/HEAD/, \"\033[1;36mH\033[00m\",\$2);gsub(/master/, \"\033[1;32mm\033[00m\",\$2);gsub(/trunk/, \"\033[1;31mt\033[00m\",\$2);print \$1 \"\t\" gensub(/([\(\)])/, \"\033[0;33m\\\\\1\033[00m\",\"g\",\$2) \$3}"'

(Is there an easier way to escape that? it was a bit tricky to work out what needed escaping)

Limit results in jQuery UI Autocomplete

I could solve this problem by adding the following content to my CSS file:

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;

Array versus linked-list

Here's a quick one: Removal of items is quicker.

Rails migration for change column

With Rails 5

From Rails Guides:

If you wish for a migration to do something that Active Record doesn’t know how to reverse, you can use reversible:

class ChangeTablenameFieldname < ActiveRecord::Migration[5.1]
  def change
    reversible do |dir|
      change_table :tablename do |t|
        dir.up   { t.change :fieldname, :date }
        dir.down { t.change :fieldname, :datetime }

Bootstrap row class contains margin-left and margin-right which creates problems

Old topic, but I was recently affected by this.

Using a class "row-fluid" instead of "row" worked fine for me but I'm not sure if it's fully supported going forward.

So after reading Why does the bootstrap .row has a default margin-left of -30px I just used the <div> (without any row class) and it behaved exactly like <div class="row-fluid">

Read files from a Folder present in project

string myFile= File.ReadAllLines(Application.StartupPath.ToString() + @"..\..\..\Data\myTxtFile.txt")

How do I call paint event?

In a method of your Form or Control, you have 3 choices:

this.Invalidate();  // request a delayed Repaint by the normal MessageLoop system    
this.Update();      // forces Repaint of invalidated area 
this.Refresh();     // Combines Invalidate() and Update()

Normally, you would just call Invalidate() and let the system combine that with other Screen updates. If you're in a hurry you should call Refresh() but then you run the risk that it will be repainted several times consecutively because of other controls (especially the Parent) Invalidating.

The normal way Windows (Win32 and WinForms.Net) handles this is to wait for the MessageQueue to run empty and then process all invalidated screen areas. That is efficient because when something changes that usually cascades into other things (controls) changing as well.

The most common scenario for Update() is when you change a property (say, label1.Text, which will invalidate the Label) in a for-loop and that loop is temporarily blocking the Message-Loop. Whenever you use it, you should ask yourself if you shouldn't be using a Thread instead. But the answer is't always Yes.

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

Problem solved. Here are the steps that I tried:

  • Enable the 32-bit application in IIS -> Application pool -> Advanced settings
  • Copy System.EnterpriseServices.dll and System.EnterpriseServices.Wrapper.dll from C:\Windows\Microsoft.NET\Framework\v2.0.50727 to the application bin folder
  • Do comments/uncomments to sections on the web.config and found that problem related to the referenced DLL.

The config that I commented the previous one that I added:

<section name="handlers" overrideModeDefault="Allow" /> 
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow"/>
  • Add the required FasterFlect.DLL used by Combres.DLL v2.1.0.0 to the application bin folder (shall download the full zip from Combres codeplex, because the required fasterflect DLL V2.0.3732.24338 cannot be found in fasterflect codeplex) and other DLLs. For convinience, use the full Combres.DLL (1,3MB)
  • Check that the DLL versions and public key tokens are configured correctly in web.config using tool, e.g. .NET Reflector

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

AFAIK, you don't need to map the UNC path to a drive letter in order to establish credentials for a server. I regularly used batch scripts like:

net use \\myserver /user:username password

:: do something with \\myserver\the\file\i\want.xml

net use /delete \\

However, any program running on the same account as your program would still be able to access everything that username:password has access to. A possible solution could be to isolate your program in its own local user account (the UNC access is local to the account that called NET USE).

Note: Using SMB accross domains is not quite a good use of the technology, IMO. If security is that important, the fact that SMB lacks encryption is a bit of a damper all by itself.

The APK file does not exist on disk

First remove cleaner by going to edit configuration, It may be cleaning the build after building the apk.

Click on edit from set run/debug then click on gradle list select the clean project item and then click on -(top 2nd from left).

How do you append rows to a table using jQuery?

The following code works

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function AddRow()
    $('#myTable').append('<tr><td>test 2</td></tr>')
<input type="button" id="btnAdd" onclick="AddRow()"/>
<a href="">test</a>
<table id="myTable">
  <tbody >

Note this will work as of jQuery 1.4 even if the table includes a <tbody> element:

jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a <tr> and inserts it into the first <tbody> in your table or wraps it into a new <tbody> if one doesn't exist.

How can I remove all files in my git repo and update/push from my local git repo?

If you prefer using GitHub Desktop, you can simply navigate inside the parent directory of your local repository and delete all of the files inside the parent directory. Then, commit and push your changes. Your repository will be cleansed of all files.

How can I get the class name from a C++ object?

An improvement for @Chubsdad answer,


using namespace std;

int main(){
A a;;

class A{
 void run();

#include <iostream>
#include <typeinfo>
void A::run(){
   cout << (string)typeid(this).name();

Which will print:

class A*

using href links inside <option> tag

Use a real dropdown menu instead: a list (ul, li) and links. Never misuse form elements as links.

Readers with screen readers usually scan through a automagically generated list of links – the’ll miss these important information. Many keyboard navigation systems (e.g. JAWS, Opera) offer different keyboard shortcuts for links and form elements.

If you still cannot drop the idea of a select don’t use the onchange handler at least. This is a real pain for keyboard users, it makes your third item nearly inaccessible.

In android how to set navigation drawer header image and name programmatically in class file?

NavigationView navigationView = (NavigationView) findViewById(; navigationView.addHeaderView(yourview);

How can I check the current status of the GPS receiver?

Setting time interval to check for fix is not a good choice.. i noticed that onLocationChanged is not called if you are not moving.. what is understandable since location is not changing :)

Better way would be for example:

  • check interval to last location received (in gpsStatusChanged)
  • if that interval is more than 15s set variable: long_interval = true
  • remove the location listener and add it again, usually then you get updated position if location really is available, if not - you probably lost location
  • in onLocationChanged you just set long_interval to false..

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

Is there a way to @Autowire a bean that requires constructor arguments?

You can also configure your component like this :

package mypackage;
import org.springframework.context.annotation.Configuration;
   public class MyConstructorClassConfig {

   public MyConstructorClass myConstructorClass(){
      return new myConstructorClass("foobar");

With the Bean annotation, you are telling Spring to register the returned bean in the BeanFactory.

So you can autowire it as you wish.

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
>>> df[df["class"]==1].count()["value"]

You could replace df["class"]==1by another condition.

Operator overloading ==, !=, Equals

public class BOX
    double height, length, breadth;

    public static bool operator == (BOX b1, BOX b2)
        if (b1 is null)
            return b2 is null;

        return b1.Equals(b2);

    public static bool operator != (BOX b1, BOX b2)
        return !(b1 == b2);

    public override bool Equals(object obj)
        if (obj == null)
            return false;

        return obj is BOX b2? (length == b2.length && 
                               breadth == b2.breadth && 
                               height == b2.height): false;


    public override int GetHashCode()
        return (height,length,breadth).GetHashCode();

Difference between if () { } and if () : endif;

Both are the same.

But: If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic. Of course it is not mandatory and you can use what ever syntax you like.

ZF uses that approach.

Angular 2 change event on every keypress

What you're looking for is

<input type="text" [(ngModel)]="mymodel" (keyup)="valuechange()" />

Then do whatever you want with the data by accessing the bound this.mymodel in your .ts file.

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

Why is my toFixed() function not working?

You're not assigning the parsed float back to your value var:

value = parseFloat(value).toFixed(2);

should fix things up.

How to change btn color in Bootstrap

If you want to override any default properties in bootstrap you have to make the properties as important.

.btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited {
    background-color: #8064A2 !important;

i hope this will works for you.

XAMPP Apache Webserver localhost not working on MAC OS

I had to disable OSX's built-in Apache server (XAMPP support thread):

sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

This allowed XAMPP to start on 80, while POW runs on 20559.

What had failed: I reconfigured /etc/apache2/httpd.conf to listen on an alternate port and rebooted OSX. No luck.

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code


The KeyEvent codes are all a part of the API:

Getting the textarea value of a ckeditor textarea with javascript

Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:

$("#CampaignTitle").bind("keyup", function()

If you really wanted a textarea change your input type text to this

<textarea id="CampaignTitle"></textarea>

Hope it helps.

How do I keep two side-by-side divs the same height?


<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>


<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!



What I did here is to change the height to min-height and gave it a fixed value. if one of them is getting resized the other one will stay the same height. not sure if this is what you want

Display the current date and time using HTML and Javascript with scrollable effects in hta application

    var today = new Date;
    document.getElementById('date').innerHTML= today.toDateString();

Android Error [Attempt to invoke virtual method 'void' on a null object reference]

I think what you want to do is cast getActivity(). For example:


This is what you need to do with the new support libraries. AppCompatActivity has replaced ActionBarActivity.

How can I get session id in php and show it?

In the PHP file first you need to register the session

 <? session_start();
     $_SESSION['id'] = $userData['user_id'];?>

And in each page of your php application you can retrive the session id

 <? session_start()
    id =  $_SESSION['id'];

How can I make a multipart/form-data POST request using Java?

I found this sample in Apache's Quickstart Guide. It's for version 4.5:

 * Example how to use multipart/form encoded POST request.
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)


            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
            } finally {
        } finally {

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.


Return None value.

>>> def test1():
...    print "In function."
>>> a = test1()
In function.
>>> print a
>>> print test1()
In function.
>>> test1()
In function.

Use return statement

>>> def test():
...   return "ACV"
>>> print test()
>>> a = test()
>>> print a

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Bootstrap Modal immediately disappearing

Same symptom, in the context of a Rails application with Bootstrap provided by the bootstrap-sass gem, and @merv's answer put me on the right track.

My application.js file had the following:

//= require bootstrap
//= require bootstrap-sprockets

The fix was to remove one of the two lines. Indeed, the gem's readme warns you about this error. My bad.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

There is no relationship between error and firewall.

first, run server program,
then run client program in another shell of python

and it will work

Adding Counter in shell script

Try this:

while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800


  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is


Get name of currently executing test in JUnit 4

String testName = null;
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (int i = trace.length - 1; i > 0; --i) {
    StackTraceElement ste = trace[i];
    try {
        Class<?> cls = Class.forName(ste.getClassName());
        Method method = cls.getDeclaredMethod(ste.getMethodName());
        Test annotation = method.getAnnotation(Test.class);
        if (annotation != null) {
            testName = ste.getClassName() + "." + ste.getMethodName();
    } catch (ClassNotFoundException e) {
    } catch (NoSuchMethodException e) {
    } catch (SecurityException e) {

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.


YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

Change MySQL default character set to UTF-8 in my.cnf?

Under Xubuntu 12.04 I simply added

character_set_server = utf8

to /etc/mysql/my.cnf

And the result is

mysql> show variables like "%character%";show variables like "%collation%";
| Variable_name            | Value                      |
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
8 rows in set (0.00 sec)

| Variable_name        | Value           |
| collation_connection | utf8_general_ci |
| collation_database   | utf8_general_ci |
| collation_server     | utf8_general_ci |
3 rows in set (0.00 sec)

Also take a look at

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

Can I use a binary literal in C or C++?

This thread may help.

/* Helper macros */
#define HEX__(n) 0x##n##LU
#define B8__(x) ((x&0x0000000FLU)?1:0) \
+((x&0x000000F0LU)?2:0) \
+((x&0x00000F00LU)?4:0) \
+((x&0x0000F000LU)?8:0) \
+((x&0x000F0000LU)?16:0) \
+((x&0x00F00000LU)?32:0) \
+((x&0x0F000000LU)?64:0) \

/* User macros */
#define B8(d) ((unsigned char)B8__(HEX__(d)))
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)<<8) \
+ B8(dlsb))
#define B32(dmsb,db2,db3,dlsb) (((unsigned long)B8(dmsb)<<24) \
+ ((unsigned long)B8(db2)<<16) \
+ ((unsigned long)B8(db3)<<8) \
+ B8(dlsb))

#include <stdio.h>

int main(void)
    // 261, evaluated at compile-time
    unsigned const number = B16(00000001,00000101);

    printf("%d \n", number);
    return 0;

It works! (All the credits go to Tom Torfs.)

Bootstrap datepicker disabling past dates without current date

to disable past date just use :

       format: 'dd/mm/yyyy',
       startDate: 'today'

Refused to load the script because it violates the following Content Security Policy directive

To elaborate some more on this, adding

script-src 'self' http://somedomain 'unsafe-inline' 'unsafe-eval';

to the meta tag like so,

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-eval'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval';  media-src *">

fixes the error.

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));


someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

Tomcat: LifecycleException when deploying

I got stuck and problem solved Don't use the path that is "Map Network Drive", but use the \server\folder structure instead

Encrypt and decrypt a password in Java

Here is the algorithm I use to crypt with MD5.It returns your crypted output.

   public class CryptWithMD5 {
   private static MessageDigest md;

   public static String cryptWithMD5(String pass){
    try {
        md = MessageDigest.getInstance("MD5");
        byte[] passBytes = pass.getBytes();
        byte[] digested = md.digest(passBytes);
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<digested.length;i++){
            sb.append(Integer.toHexString(0xff & digested[i]));
        return sb.toString();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CryptWithMD5.class.getName()).log(Level.SEVERE, null, ex);
        return null;


You cannot decrypt MD5, but you can compare outputs since if you put the same string in this method it will have the same crypted output.If you want to decrypt you need to use the SHA.You will never use decription for a users password.For that always use MD5.That exception is pretty redundant.It will never throw it.

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join -

C# "No suitable method found to override." -- but there is one

Make sure that you have the child class explicitly inherit the parent class:

public class Ext : Base { // stuff }

Print a variable in hexadecimal in Python

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef

Chrome DevTools Devices does not detect device when plugged in

If you have andorid 9 in your mobile you must update Android SDK in Android Studio.

  • Open Android studio and go to Settings.
  • System Settings\Android
  • Select Android SDK (You will see new version of SDK)
  • Click to apply
  • You mobile phone will want to access now on MIDI mode.

How do you synchronise projects to GitHub with Android Studio?

Github with android studio

/*For New - Run these command in terminal*/
echo "# Your Repository" >>
git init
git add
git commit -m "first commit"
git remote add origin
git push -u origin master

/*For Exist - Run these command in terminal*/
git remote add origin
git push -u origin master
//git push -f origin master
//git push origin master --force

/*For Update - Run these command in terminal*/
git add .
git commit -m "your message"
git push

Any way to clear python's IDLE window?

None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window.

CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).

PROS: Retains any window customization you've made (color, font-size).

Is there more to an interface than having the correct methods

The purpose of interfaces is abstraction, or decoupling from implementation.

If you introduce an abstraction in your program, you don't care about the possible implementations. You are interested in what it can do and not how, and you use an interface to express this in Java.

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:


Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

How to loop through all elements of a form jQuery

From the jQuery :input selector page:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

This is the best choice.

$('#new_user_form *').filter(':input').each(function(){
    //your code here

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.

To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */

jsFiddle demo

1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Html.EditorFor Set Default Value

This worked for me:

In the controller

*ViewBag.DefaultValue= "Default Value";*

In the View

*@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter a Value", @Value = ViewBag.DefaultValue} })*

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

How to compare two strings are equal in value, what is the best method?

You should use some form of the String#equals(Object) method. However, there is some subtlety in how you should do it:

If you have a string literal then you should use it like this:


This is because the string literal "Hello" can never be null, so you will never run into a NullPointerException.

If you have a string and another object then you should use:


You can make sure you are actually getting string equality by doing this. For all you know, myObject could be of a class that always returns true in its equals method!

Start with the object less likely to be null because this:

String foo = null;
String bar = "hello";

will throw a NullPointerException, but this:

String foo = null;
String bar = "hello";

will not. String#equals(Object) will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

How do you implement a circular buffer in C?

The simplest solution would be to keep track of the item size and the number of items, and then create a buffer of the appropriate number of bytes:

typedef struct circular_buffer
    void *buffer;     // data buffer
    void *buffer_end; // end of data buffer
    size_t capacity;  // maximum number of items in the buffer
    size_t count;     // number of items in the buffer
    size_t sz;        // size of each item in the buffer
    void *head;       // pointer to head
    void *tail;       // pointer to tail
} circular_buffer;

void cb_init(circular_buffer *cb, size_t capacity, size_t sz)
    cb->buffer = malloc(capacity * sz);
    if(cb->buffer == NULL)
        // handle error
    cb->buffer_end = (char *)cb->buffer + capacity * sz;
    cb->capacity = capacity;
    cb->count = 0;
    cb->sz = sz;
    cb->head = cb->buffer;
    cb->tail = cb->buffer;

void cb_free(circular_buffer *cb)
    // clear out other fields too, just to be safe

void cb_push_back(circular_buffer *cb, const void *item)
    if(cb->count == cb->capacity){
        // handle error
    memcpy(cb->head, item, cb->sz);
    cb->head = (char*)cb->head + cb->sz;
    if(cb->head == cb->buffer_end)
        cb->head = cb->buffer;

void cb_pop_front(circular_buffer *cb, void *item)
    if(cb->count == 0){
        // handle error
    memcpy(item, cb->tail, cb->sz);
    cb->tail = (char*)cb->tail + cb->sz;
    if(cb->tail == cb->buffer_end)
        cb->tail = cb->buffer;

How to call Stored Procedure in Entity Framework 6 (Code-First)?

.NET Core 5.0 does not have FromSql instead it has FromSqlRaw

All below worked for me. Account class here is Entity in C# with exact same table and column names as in the database.

App configuration class as below

class AppConfiguration
    public AppConfiguration()
        var configBuilder = new ConfigurationBuilder();
        var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        configBuilder.AddJsonFile(path, false);
        var root = configBuilder.Build();
        var appSetting = root.GetSection("ConnectionStrings:DefaultConnection");
        sqlConnectionString = appSetting.Value;

    public string sqlConnectionString { get; set; }

DbContext class:

public class DatabaseContext : DbContext
    public class OptionsBuild
        public OptionsBuild()
            setting = new AppConfiguration();
            opsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
            dbOptions = opsBuilder.Options;

        public DbContextOptionsBuilder<DatabaseContext> opsBuilder { get; set; }
        public DbContextOptions<DatabaseContext> dbOptions { get; set; }

        private AppConfiguration setting { get; set; }

    public static OptionsBuild ops = new OptionsBuild();

    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        //disable initializer
        //  Database.SetInitializer<DatabaseContext>(null);

    public DbSet<Account> Account { get; set; }

This code should be in your data access layer:

List<Account> accounts = new List<Account>();
var context = new DatabaseContext(DatabaseContext.ops.dbOptions);
accounts = await context.Account.ToListAsync();   //direct select from a table

var param = new SqlParameter("@FirstName", "Bill");
accounts = await context.Account.FromSqlRaw<Account>("exec Proc_Account_Select", 
param).ToListAsync();            //procedure call with parameter
accounts = context.Account.FromSqlRaw("SELECT * FROM dbo.Account").ToList();  //raw query

Get file size before uploading

Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.

In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.

How do format a phone number as a String in Java?

You could also use Here is an example:


String s = "18005551234";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(s, Locale.US.getCountry());
String formatted = phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);

Here you can get the library on your classpath:

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

I solved this issue with right click on project -> Set as Main Project.

Get specific object by id from array of objects in AngularJS

$scope.olkes = [{'id':11, 'name':'---Z?hm?t olmasa seçim edin---'},
                {'id':15, 'name':'Türky?'},
                {'id':45, 'name':'Az?rbaycan'},
                {'id':60, 'name':'Rusya'},
                {'id':64, 'name':'Gürcüstan'},
                {'id':65, 'name':'Qazaxistan'}];

<span>{{(olkes | filter: {id:45})[0].name}}</span>

output: Az?rbaycan

Return date as ddmmyyyy in SQL Server

I've been doing it like this for years;

print convert(char,getdate(),103)

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

There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.

Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.

const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });

Moment JS start and end of given month

const year = 2014;_x000D_
const month = 09;_x000D_
// months start at index 0 in momentjs, so we subtract 1_x000D_
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");_x000D_
// get the number of days for this month_x000D_
const daysInMonth = moment(startDate).daysInMonth();_x000D_
// we are adding the days in this month to the start date (minus the first day)_x000D_
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");_x000D_
console.log(`start date: ${startDate}`);_x000D_
console.log(`end date:   ${endDate}`);

How can I execute Python scripts using Anaconda's version of Python?

don't know windows 8 but you can probably set the default prog for a specific extension, for example on windows 7 you do right click => open with, then you select the prog you want and select 'use this prog as default', or you can remove your old version of python from your path and add the one of the anaconda

How do I run a command on an already existing Docker container?

A quick way to resume and access the most recently exited container:

docker start -a -i `docker ps -q -l`

Subclipse svn:ignore

This is just a WAG as I am not a Subclipse user, but have you ensured that the folders containing what you're trying to ignore have themselves been added to SVN? You can't svn:ignore something inside a folder that's not under version control.

customize Android Facebook Login button

  1. Create custom facebook button and change visability on native facebook button:

                android:textColor="@color/colorAccent" />
                android:layout_marginBottom="12dp" />
  2. Add listener to your fake button and simulate click:

    public void onClick(View v) {
        if (v.getId() =={

A failure occurred while executing

I removed this issue by adding the following lines

add multiDexEnabled true in android>app>build.gradle inside defaultConfig

add implementation '' in android>app>build.gradle inside dependencies

What does @@variable mean in Ruby?

A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. Check out the following example; its output is in the comments at the end of the puts lines:

class Test
  @@shared = 1

  def value

  def value=(value)
    @@shared = value

class AnotherTest < Test; end

t =
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2

x =
puts "x.value is #{x.value}" # 2

a =
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3

You can see that @@shared is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared, with one @, would not be.


As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class class, but only the instance of the Class class you're working with. An example:

class Polygon
  class << self
    attr_accessor :sides

class Triangle < Polygon
  @sides = 3

class Rectangle < Polygon
  @sides = 4

class Square < Rectangle

class Hexagon < Polygon
  @sides = 6

puts "Triangle.sides:  #{Triangle.sides.inspect}"  # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides:    #{Square.sides.inspect}"    # nil
puts "Hexagon.sides:   #{Hexagon.sides.inspect}"   # 6

I included the Square example (which outputs nil) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.

Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.

How to order events bound with jQuery

Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.

If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.

$( '#mybutton' ).click( function(e) { 
    // Do stuff first
} );

$( '#mybutton' ).click( function(e) { 
    // Do other stuff first
} );

$( document ).delegate( '#mybutton', 'click', function(e) {
    // Do stuff last
} );

Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last:

Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.

what is the use of fflush(stdin) in c programming

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

sys.argv[1] meaning in script

I would like to note that previous answers made many assumptions about the user's knowledge. This answer attempts to answer the question at a more tutorial level.

For every invocation of Python, sys.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming convention in which argv and argc represent the command line arguments.

You'll want to learn more about lists and strings as you're familiarizing yourself with Python, but in the meantime, here are a few things to know.

You can simply create a script that prints the arguments as they're represented. It also prints the number of arguments, using the len function on the list.

from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))

The script requires Python 2.6 or later. If you call this script, you can invoke it with different arguments to see what happens.

> python
[''] 1

> python foo and bar
['', 'foo', 'and', 'bar'] 4

> python "foo and bar"
['', 'foo and bar'] 2

> python "foo and bar" and baz
['', 'foo and bar', 'and', 'baz'] 4

As you can see, the command-line arguments include the script name but not the interpreter name. In this sense, Python treats the script as the executable. If you need to know the name of the executable (python in this case), you can use sys.executable.

You can see from the examples that it is possible to receive arguments that do contain spaces if the user invoked the script with arguments encapsulated in quotes, so what you get is the list of arguments as supplied by the user.

Now in your Python code, you can use this list of strings as input to your program. Since lists are indexed by zero-based integers, you can get the individual items using the list[0] syntax. For example, to get the script name:

script_name = sys.argv[0] # this will always work.

Although interesting, you rarely need to know your script name. To get the first argument after the script for a filename, you could do the following:

filename = sys.argv[1]

This is a very common usage, but note that it will fail with an IndexError if no argument was supplied.

Also, Python lets you reference a slice of a list, so to get another list of just the user-supplied arguments (but without the script name), you can do

user_args = sys.argv[1:] # get everything after the script name

Additionally, Python allows you to assign a sequence of items (including lists) to variable names. So if you expect the user to always supply two arguments, you can assign those arguments (as strings) to two variables:

user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2

So, to answer your specific question, sys.argv[1] represents the first command-line argument (as a string) supplied to the script in question. It will not prompt for input, but it will fail with an IndexError if no arguments are supplied on the command-line following the script name.

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Replace image src location using CSS

You could do this but it is hacky

.application-title {
   /* set these dims according to your image size */

.application-title img {

Here is a working example:

HTML5 Video tag not working in Safari , iPhone and iPad

I know this is an old post, but the issue still seems to surface under different server environments. None of the above were the solution for me. In my case it came down to web optimization and making use gzip, or rather needing to disable it for videos.

I added this to my htaccess file and it took care it. SetEnvIfNoCase Request_URI .(?:ogv|ogg|oga|m4v|mp4|m4a|mov|mp3|wav|webma?|webmv)$ no-gzip dont-vary

I was already using these attributes on my tag: controls playsinline

How to add New Column with Value to the Existing DataTable?

//Data Table

 protected DataTable tblDynamic
                return (DataTable)ViewState["tblDynamic"];
                ViewState["tblDynamic"] = value;
//DynamicReport_GetUserType() function for getting data from DB

System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];

//Add Column as "TypeName"

                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));

//fill column data against ds.Tables[13]

                for (int i = 0; i < tblDynamic.Rows.Count; i++)

                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                        tblDynamic.Rows[i]["TypeName"] = "Dog;

How many threads can a Java VM support?

The absolute theoretical maximum is generally a process's user address space divided by the thread stack size (though in reality, if all your memory is reserved for thread stacks, you won't have a working program...).

So under 32-bit Windows, for example, where each process has a user address space of 2GB, giving each thread a 128K stack size, you'd expect an absolute maximum of 16384 threads (=2*1024*1024 / 128). In practice, I find I can start up about 13,000 under XP.

Then, I think you're essentially into whether (a) you can manage juggling that many threads in your code and not do obviously silly things (such as making them all wait on the same object then calling notifyAll()...), and (b) whether the operating system can. In principle, the answer to (b) is "yes" if the answer to (a) is also "yes".

Incidentally, you can specify the stack size in the constructor of the Thread; you don't need to (and probably shouldn't) mess about with VM parameters for this.

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';


   object(stdClass)#2 (1) {
      string(10) "Here we go"

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Asynchronous Function Call in PHP

Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).

The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.

The advantages are:

  1. Scalability - you can just add worker nodes to keep up with demand. In this way, tasks are run in parallel.
  2. Reliability - modern queue managers such as RabbitMQ, ZeroMQ, Redis, etc, are made to be extremely reliable.

Single Result from Database by using mySQLi

When just a single result is needed, then no loop should be used. Just fetch the row right away.

  • In case you need to fetch the entire row into associative array:

      $row = $result->fetch_assoc();
  • in case you need just a single value

      $row = $result->fetch_row();
      $value = $row[0] ?? false;

The last example will return the first column from the first returned row, or false if no row was returned. It can be also shortened to a single line,

$value = $result->fetch_row()[0] ?? false;

Below are complete examples for different use cases

Variables to be used in the query

When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id:

$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$result = $stmt->get_result();
$row = $result->fetch_assoc();

// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;

The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question

No variables in the query

In your case, where no variables to be used in the query, you can use the query() method:

$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;

By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:

// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;

// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);

As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).

How to get images in Bootstrap's card to be the same height/width?

Each of the images need to be the exact dimensions before you put them up otherwise bootstrap 4 will try to place them in a funky shape. Bootstrap also has something like Masonry on their documents that you can use if need be, you can see that here,

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use to make the text area act more like a div.


<textarea class="hidden" rows="4" cols="50">


$("#hiddentextarea").change(function() {

alert('Textarea changed');


Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

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

With the constructor:

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

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

Converting URL to String and back again

Swift 5.

To convert a String to a URL:

let stringToURL = URL(string: "your-string")

To convert a URL to a String:

let urlToString = stringToURL?.absoluteString

Completely removing phpMyAdmin

I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.

sudo apt-get purge libapache2-mod-php5

sudo apt-get install libapache2-mod-php5

sudo apt-get purge phpmyadmin

sudo apt-get install phpmyadmin

sudo /etc/init.d/apache2 restart

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

You said programmatically, right? I hope C# is ok. I know you said that you tried SMO and it didn't quite do what you wanted, so this probably won't be perfect for your request, but it will programmatically read out legit SQL statements that you could run to recreate the stored procedure. If it doesn't have the GO statements that you want, you can probably assume that each of the strings in the StringCollection could have a GO after it. You may not get that comment with the date and time in it, but in my similar sounding project (big-ass deployment tool that has to back up everything individually), this has done rather nicely. If you have a prior base that you wanted to work from, and you still have the original database to run this on, I'd consider tossing the initial effort and restandardizing on this output.

using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
string connectionString = … /* some connection string */;
ServerConnection sc = new ServerConnection(connectionString);
Server s = new Server(connection);
Database db = new Database(s, … /* database name */);
StoredProcedure sp = new StoredProcedure(db, … /* stored procedure name */);
StringCollection statements = sp.Script;

Resync git repo with new .gitignore file

The solution mentioned in ".gitignore file not ignoring" is a bit extreme, but should work:

# rm all files
git rm -r --cached .
# add all files as per new .gitignore
git add .
# now, commit for new .gitignore to apply
git commit -m ".gitignore is now working"

(make sure to commit first your changes you want to keep, to avoid any incident as jball037 comments below.
The --cached option will keep your files untouched on your disk though.)

You also have other more fine-grained solution in the blog post "Making Git ignore already-tracked files":

git rm --cached `git ls-files -i --exclude-standard`

Bassim suggests in his edit:

Files with space in their paths

In case you get an error message like fatal: path spec '...' did not match any files, there might be files with spaces in their path.

You can remove all other files with option --ignore-unmatch:

git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`

but unmatched files will remain in your repository and will have to be removed explicitly by enclosing their path with double quotes:

git rm --cached "<>"

ShowAllData method of Worksheet class failed

The simple way to avoid this is not to use the worksheet method ShowAllData

Autofilter has the same ShowAllData method which doesn't throw an error when the filter is enabled but no filter is set

If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData

Java default constructor

A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()

public Module(){

What is "String args[]"? parameter in main method Java

I think it's pretty well covered by the answers above that String args[] is simply an array of string arguments you can pass to your application when you run it. For completion, I might add that it's also valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:

public static void main (String... args)

In other words, the main method must accept either a String array (String args[]) or varargs (String... args) as a method argument. And there is no magic with the name args either. You might as well write arguments or even freddiefujiwara as shown in below

public static void main (String[] arguments)

public static void main (String[] freddiefujiwara)

How to assign an exec result to a sql variable?

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;

So yes, it should work that way.

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

Printing without newline (print 'a',) prints a space, how to remove?


It's pretty long time ago

Now, In python 3.x it will be pretty easy


for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code



More about print() function




you can print multiple values using commas

sep = '-'

3 values will be separated by '-' character

you can use any character instead of that even string like sep='@' or sep='good'


by default print function put '\n' charater at the end of output

but you can use any character or string by changing end variale value

like end='$' or end='.' or end='Hello'


this is a default value, system standard output

using this argument you can create a output file stream like

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txt where your output I am a Programmer will be stored

flush = False

It's a default value using flush=True you can forcibly flush the stream

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

If REST applications are supposed to be stateless, how do you manage sessions?

I see that the basic issue here is mixing up Session with State. And while REST specifies that you should NOT store the State on the server, nothing prevents you from storing a user Session.

Managing the State on the server means that your server knows exactly what the client is doing (what page they're viewing in which section of the application). And this is what you shouldn't need to do.

I agree with the other people saying that you should keep the session storage to a minimum size; and while that's common sense, it's actually also dependent on the application. So, in short, you can still keep a session with cached data to handle the requests with less load on the server, and manage the authentication by providing a temporary authentication/access token for the client to use. Whenever the session/token is expired, generate a new one and ask the client to use it.

Someone might argue that the client should better generate the token. I say it works both ways, and it would depend on the application, and who's going to work with the API.

Also keeping some sensitive session data on the server should be the right way to do. You cannot trust the client to keep their shopping cart that (for example) contains a field named "isFreeGift". Such information should be kept on the server.

The video link provided by Santanu Dey in his answer is helpful. Watch it if you haven't.

Just a side note: It seems all the answers already given seem to disregard the fact that some operations could cause a heavy load on the server. That's relevant in terms of power consumption, hardware consumption, and cost (for servers rented by CPU cycle). A good developer shouldn't be lazy in optimizing their application, even if the operation can be done very quickly on a modern CPU on some rented server for which they don't pay its electricity and maintenance bill.

Althoght the question is a few years old, I hope that my answer would still be helpful.

Passing data between controllers in Angular JS?

angular.module('testAppControllers', [])
    .controller('ctrlOne', function ($scope) {
    .controller('ctrlTwo', function ($scope) {
        $scope.$on('test', function() {

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

Determine the type of an object?

You can use type() or isinstance().

>>> type([]) is list

Be warned that you can clobber list or any other type by assigning a variable in the current scope of the same name.

>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'

Above we see that dict gets reassigned to a string, therefore the test:

type({}) is dict


To get around this and use type() more cautiously:

>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
>>> dict =""
>>> type({}) is dict
>>> type({}) is __builtin__.dict

Visual Studio : short cut Key : Duplicate Line

Ctrl + D is a new shortcut introduced in VS 2017 v15.6 that seems to do the exact thing that Ctrl + E, V

Ctrl + D will duplicate the line the cursor is in and insert it right below the line in focus. If you’d like to duplicate a specific set of code, simply select the portion of code you want to duplicate before invoking the duplicate code command.

It won't affect your clipboard


Retrieving the COM class factory for component failed

In case it helps somebody:

I am running Windows 7 64-bit and I wanted to register a 32-bit dll.

First I tried: regsvr32 and got the following error:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {A1D59B81-C868-4F66-B58F-AC94A4A7982E} failed due to the following error: 80040154.

Then I tried to add the application through the Component Services (Run->DCCOMCNFG) ( and got the following error:

System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {A1D59B81-C868-4F66-B58F-AC94A4A7982E} failed due to the following error: 80070005.

There are many links to solving it but what worked for me was: Console Root -> Component Services -> Computers -> My Computer -> COM+ Applications -> your_application_name -> Properties: Security tab: Authorization: Uncheck 'Enforce access checks for this application'.

I don't know what it does.

How to get the current date and time of your timezone in Java?

Check this may be helpful. Works fine for me. Code also covered daylight savings

    TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
    Calendar cal = Calendar.getInstance();      
    // If needed in hours rather than milliseconds
    int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));        
    int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));       
    int dts = cal.getTimeZone().getDSTSavings();
    System.out.println("Local Time Zone : " + cal.getTimeZone().getDisplayName());
    System.out.println("Local Day Light Time Saving : " + dts);
    System.out.println("China Time : " + tz.getRawOffset());
    System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
    System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);    
    // Adjust to GMT
    // Adjust to Daylight Savings
    cal.add(Calendar.MILLISECOND, - cal.getTimeZone().getDSTSavings());
    // Adjust to Offset
    cal.add(Calendar.MILLISECOND, tz.getRawOffset());       
    Date dt = new Date(cal.getTimeInMillis());              
    System.out.println("After adjusting offset Acctual China Time :" + dt); 

Making text bold using attributed string in swift

Building on Jeremy Bader and David West's excellent answers, a Swift 3 extension:

extension String {
    func withBoldText(boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString {
        let nonBoldFontAttribute = [NSFontAttributeName:font!]
        let boldFontAttribute = [NSFontAttributeName:boldFont!]
        let boldString = NSMutableAttributedString(string: self as String, attributes:nonBoldFontAttribute)
        for i in 0 ..< boldPartsOfString.count {
            boldString.addAttributes(boldFontAttribute, range: (self as NSString).range(of: boldPartsOfString[i] as String))
        return boldString


let label = UILabel()
let font = UIFont(name: "AvenirNext-Italic", size: 24)!
let boldFont = UIFont(name: "AvenirNext-BoldItalic", size: 24)!
label.attributedText = "Make sure your face is\nbrightly and evenly lit".withBoldText(
    boldPartsOfString: ["brightly", "evenly"], font: font, boldFont: boldFont)

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

"Input string was not in a correct format."

In my case I forgot to put double curly brace to escape. {{myobject}}

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.

@font-face {
font-family: 'glyphicons-halflings-regular'; 
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}

Software Design vs. Software Architecture

In some descriptions of the SDLC (Software Development Life Cycle) they are interchangeable, but the consesus is that they are distinct. They are at the same time: different (1) stages, (2) areas of responsibility, and (3) levels of decision-making.

  • Architecture is the bigger picture: the choice of frameworks, languages, scope, goals, and high-level methodologies (Rational, waterfall, agile, etc.).
  • Design is the smaller picture: the plan for how code will be organized; how the contracts between different parts of the system will look; the ongoing implementation of the project's methodologies and goals. Specification are written during this stage.

These two stages will seem to blend together for different reasons.

  1. Smaller projects often don't have enough scope to separate out planning into these to stages.
  2. A project might be a part of a larger project, and hence parts of both stages are already decided. (There are already existing databases, conventions, standards, protocols, frameworks, reusable code, etc.)
  3. Newer ways of thinking about the SDLC (see Agile methodologies) somewhat rearrange this traditional approach. Design (architecture to a lesser extent) takes place throughout the SDLC on purpose. There are often more iterations where the whole process happens over and over.
  4. Software development is complicated and difficult to plan anyway, but clients/managers/salespeople usually make it harder by changing goals and requirements mid-stream. Design and even architectural decisions must bemade later in the project whether that is the plan or not.

Even if the stages or areas of responsibility blend together and happen all over the place, it is always good to know what level of decision-making is happening. (We could go on forever with this. I'm trying to keep it a summary.) I'll end with: Even if it seems your project has no formal architectural or design stage/AOR/documentaiton, it IS happening whether anyone is consciously doing it or not. If no one decides to do architecture, then a default one happens that is probably poor. Ditto for design. These concepts are almost more important if there are no formal stages representing them.

Read all contacts' phone numbers in android

This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.

package com.test;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                              null, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {

                if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
                            ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
                    String id = cur.getString(cur.getColumnIndex(
                    String name = cur.getString(cur.getColumnIndex(
                    Cursor pCur = cr.query(
                                    + " = ?", new String[] { id }, null);
                    int i = 0;
                    int pCount = pCur.getCount();
                    String[] phoneNum = new String[pCount];
                    String[] phoneType = new String[pCount];
                    while (pCur != null && pCur.moveToNext()) {
                        phoneNum[i] = pCur.getString(pCur.getColumnIndex(
                        phoneType[i] = pCur.getString(pCur.getColumnIndex(




Connect to external server by using phpMyAdmin

You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file ( for you. This file is found at the root of the phpMyAdmin directory.

Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.

You now have only to move the file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.

Don't forget to delete the config folder afterwards.

iframe refuses to display

The reason for the error is that the host server for has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.

Check out this link on Content Security Policy for more details.

Convert command line argument to string

Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:

std::string dump_name;


    fprintf(stdout, "ARGUMENT %s", dump_name.c_str());

Note the use of assign, and also the need for the c_str() function call.

Iterator over HashMap in Java

Can we see your import block? because it seems that you have imported the wrong Iterator class.

The one you should use is java.util.Iterator

To make sure, try:

java.util.Iterator iter = hm.keySet().iterator();

I personally suggest the following:

Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

Map<Integer, String> hm = new HashMap<>();

and for the loop:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));

UPDATE 3/5/2015

Found out that iterating over the Entry set will be better performance wise:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();


UPDATE 10/3/2017

For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";"POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Unioning two tables with different number of columns

if only 1 row, you can use join

Select t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Col5 from Table1 t1 join Table2 t2;

The name 'model' does not exist in current context in MVC3

Closing Visual Studio and re-opening worked for me. Must be a weird bug.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to:

Hope this helps.

What does "async: false" do in jQuery.ajax()?

One use case is to make an ajax call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.

            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}

Difference between jar and war in Java

JAR files allow to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications.

JAR can be created with any desired structure. In contrast, WAR has a predefined structure with WEB-INF and META-INF directories.

A JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.

Find and Replace text in the entire table using a MySQL query

I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin ( who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…

Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…

UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid` 
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

To test the expected result you may want to use :

SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

jQuery - trapping tab select event

Simply use the on click event for tab shown.

$(document).on('', 'a[href="#tab"]', function (){

How do I get the path of the assembly the code is in?

Web application?


Remove title in Toolbar in appcompat-v7

The correct way to hide/change the Toolbar Title is this:

Toolbar toolbar = (Toolbar) findViewById(;

This because when you call setSupportActionBar(toolbar);, then the getSupportActionBar() will be responsible of handling everything to the Action Bar, not the toolbar object.

See here

Javamail Could not convert socket to TLS GMail

I got similar problem when default SSL protocol for sending emails was set to TLSv1 and smtp server was not supporting this protocol anymore. Trick was to use newer protocol:


Parsing arguments to a Java command line program

Here is @DwB solution upgraded to Commons CLI 1.3.1 compliance (replaced deprecated components OptionBuilder and GnuParser). The Apache documentation uses examples that in real life have unmarked/bare arguments but ignores them. Thanks @DwB for showing how it works.

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public static void main(String[] parameters) {
    CommandLine commandLine;
    Option option_A = Option.builder("A").argName("opt3").hasArg().desc("The A option").build();
    Option option_r = Option.builder("r").argName("opt1").hasArg().desc("The r option").build();
    Option option_S = Option.builder("S").argName("opt2").hasArg().desc("The S option").build();
    Option option_test = Option.builder().longOpt("test").desc("The test option").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();


    String header = "               [<arg1> [<arg2> [<arg3> ...\n       Options, flags and arguments may be in any order";
    String footer = "This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated methods replaced)";
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("CLIsample", header, options, footer, true);    

    String[] testArgs =
            { "-r", "opt1", "-S", "opt2", "arg1", "arg2",
                    "arg3", "arg4", "--test", "-A", "opt3", };

        commandLine = parser.parse(options, testArgs);

        if (commandLine.hasOption("A"))
            System.out.print("Option A is present.  The value is: ");

        if (commandLine.hasOption("r"))
            System.out.print("Option r is present.  The value is: ");

        if (commandLine.hasOption("S"))
            System.out.print("Option S is present.  The value is: ");

        if (commandLine.hasOption("test"))
            System.out.println("Option test is present.  This is a flag option.");

            String[] remainder = commandLine.getArgs();
            System.out.print("Remaining arguments: ");
            for (String argument : remainder)
                System.out.print(" ");


    catch (ParseException exception)
        System.out.print("Parse error: ");



usage: CLIsample [-A <opt3>] [-r <opt1>] [-S <opt2>] [--test]
                 [<arg1> [<arg2> [<arg3> ...
       Options, flags and arguments may be in any order
 -A <opt3>   The A option
 -r <opt1>   The r option
 -S <opt2>   The S option
    --test   The test option
This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated
methods replaced)
Option A is present.  The value is: opt3
Option r is present.  The value is: opt1
Option S is present.  The value is: opt2
Option test is present.  This is a flag option.
Remaining arguments: arg1 arg2 arg3 arg4

Global Events in Angular

Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

But make sure to unsubscribe to that on destroy of the parent component.

Make a link use POST instead of GET

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

<script type="text/javascript" language="javascript">
function post_link(data){


   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>

Visual Studio Code Tab Key does not insert a tab

As of December 2018 on macOS Mojave 10.14.2 using VSCode 1.29.1 the default keybinding for 'Toggle Tab Key Moves Focus' is set to Command+Shift+M. If you got stuck with this, using that key combo should fix the issue.

Do Command+K Command+S to pull up the Hotkeys Settings and then search for Toggle Tab Key Moves Focus or editor.action.toggleTabFocusMode if you want to change the key combo.

MVC razor form with multiple different submit buttons?

This elegant solution works for number of submit buttons:

  // Html code here
  <input type="submit" name="command" value="submit1" />
  <input type="submit" name="command" value="submit2" />


And in your controllers' action method accept it as a parameter.

public ActionResult Create(Employee model, string command)
      // Call action here...
      // Call another action here...

Skip Git commit hooks

From man githooks:

This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 class:

import UIKit

class CircleView: UIView {

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {return}
        context.addEllipse(in: rect)

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
          return key+"="+encodeURIComponent(params[key])

And you would use it this way to build a request.

var endpoint = ""
var params = {
  a: 1, 
  b: 2,
  c: 3

var url = endpoint + formatParams(params)
//=> ""

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

How to center a <p> element inside a <div> container?

You only need to add text-align: center to your <div>

In your case also remove both styles that you added to your <p>.

Check out the demo here:

Good Luck

Pylint "unresolved import" error in Visual Studio Code

My solution

This solution is only for the current project.

  1. In the project root, create folder .vscode

  2. Then create the file .vscode/settings.json

  3. In the file setting.json, add the line (this is for Python 3)

        "python.pythonPath": "/usr/local/bin/python3",
  4. This is the example for Python 2

        "python.pythonPath": "/usr/local/bin/python",
  5. If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.

  6. This example works for dockerized Python - Django.

localhost refused to connect Error in visual studio

rebooting the machine was the only thing that worked for me

Truncate Decimal number not Round Off

Here's an extension method which does not suffer from integer overflow (like some of the above answers do). It also caches some powers of 10 for efficiency.

static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };
public static double Truncate(this double x, int precision)
    if (precision < 0)
        throw new ArgumentException();
    if (precision == 0)
        return Math.Truncate(x);
    double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];
    return Math.Truncate(x * m) / m;

Format number to 2 decimal places

Just use format(number, qtyDecimals) sample: format(1000, 2) result 1000.00

Unable to resolve host "<URL here>" No address associated with host name

Unable to resolve host “”; No address associated with hostname

I had this issue and I solved it by this way. change



http://ipaddress/abc/def/ghi/name.php //http://97.68.XX.YY/abc/def/ghi/name.php

I solved this by this have to give server ip address instead of hostname/servername.

Please try this and comment your feedback.

"No cached version... available for offline mode."

For mac, Uncheck Offline Work from Preference -> Build, Execution, Deployment -> Build Tools -> Gradle -> Global Gradle Settings

tip: cmd+, to open Preference via shortcut key

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!, 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!, length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$'}" to the md-select tag ash shown in this pen


<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$'}">_x000D_
  <md-select-label>{{ user ? : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{}}</md-option>_x000D_

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd

This will almost certainly be faster than the conversion to and from a date.

Python how to plot graph sine wave

import numpy as np
import matplotlib.pyplot as plt

F = 5.e2          # No. of cycles per second, F = 500 Hz
T = 2.e-3         # Time period, T = 2 ms
Fs = 50.e3        # No. of samples per second, Fs = 50 kHz
Ts = 1./Fs        # Sampling interval, Ts = 20 us
N = int(T/Ts)     # No. of samples for 2 ms, N = 100

t = np.linspace(0, T, N)
signal = np.sin(2*np.pi*F*t)

plt.plot(t, signal)
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I have exactly the same issue. I ran a couple of virtual hosts on my local machine for developing.

First, I changed /etc/apache2/conf-available/php5-fpm.conf. I replaced every

Order Deny,Allow
Deny from all


Require all granted

The configuration has to be enabled by a2enconf php5-fpm. I did the same with my virtual hosts configurations and made the replacements.

I think this is not advised for security reasons, but as long as I use my server for local purposes only I can live with it.

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

It's important to note that using viewDidLoad for positioning is a bit risky and should be avoided since the bounds are not set. this may cause unexpected results (I had a variety of issues...)

This post describes quite well the different methods and what happens in each of them.

currently for one-time init and positioning I'm thinking of using viewDidAppear with a flag, if anyone has any other recommendation please let me know.

How to update only one field using Entity Framework?

I know this is an old thread but I was also looking for a similar solution and decided to go with the solution @Doku-so provided. I'm commenting to answer the question asked by @Imran Rizvi , I followed @Doku-so link that shows a similar implementation. @Imran Rizvi's question was that he was getting an error using the provided solution 'Cannot convert Lambda expression to Type 'Expression> [] ' because it is not a delegate type'. I wanted to offer a small modification I made to @Doku-so's solution that fixes this error in case anyone else comes across this post and decides to use @Doku-so's solution.

The issue is the second argument in the Update method,

public int Update(T entity, Expression<Func<T, object>>[] properties). 

To call this method using the syntax provided...

Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn); 

You must add the 'params' keyword in front of the second arugment as so.

public int Update(T entity, params Expression<Func<T, object>>[] properties)

or if you don't want to change the method signature then to call the Update method you need to add the 'new' keyword, specify the size of the array, then finally use the collection object initializer syntax for each property to update as seen below.

Update(Model, new Expression<Func<T, object>>[3] { d=>d.Name }, { d=>d.SecondProperty }, { d=>d.AndSoOn });

In @Doku-so's example he is specifying an array of Expressions so you must pass the properties to update in an array, because of the array you must also specify the size of the array. To avoid this you could also change the expression argument to use IEnumerable instead of an array.

Here is my implementation of @Doku-so's solution.

public int Update<TEntity>(LcmsEntities dataContext, DbEntityEntry<TEntity> entityEntry, params Expression<Func<TEntity, object>>[] properties)
     where TEntity: class
        entityEntry.State = System.Data.Entity.EntityState.Unchanged;

            .ForEach((property) =>
                var propertyName = string.Empty;
                var bodyExpression = property.Body;
                if (bodyExpression.NodeType == ExpressionType.Convert
                    && bodyExpression is UnaryExpression)
                    Expression operand = ((UnaryExpression)property.Body).Operand;
                    propertyName = ((MemberExpression)operand).Member.Name;
                    propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);

                entityEntry.Property(propertyName).IsModified = true;

        dataContext.Configuration.ValidateOnSaveEnabled = false;

        return dataContext.SaveChanges();


this.Update<Contact>(context, context.Entry(modifiedContact), c => c.Active, c => c.ContactTypeId);

@Doku-so provided a cool approach using generic's, I used the concept to solve my issue but you just can't use @Doku-so's solution as is and in both this post and the linked post no one answered the usage error questions.

Import error No module named skimage

OSX python3

Just run this code in your terminal:

sudo pip3 install scikit-image

If you faced any other issues please check this link for more.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 


1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Turn off iPhone/Safari input element rounding

Here is the complete solution for Compass (SCSS):

input {
  -webkit-appearance: none;  // remove shadow in iOS
  @include border-radius(0);  // remove border-radius in iOS

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

Show diff between commits

I always love using the command line and have user friendly tools (with GUI) at my hand. Best of both worlds. Here is how I do it to compare two commits in Git.

You can show the diff between two commits like the following.

Edit your git config file in a TEXT EDITOR:

git config --global -e 

Set up a proper diff tool (user friendly) like Meld like this in Windows in the Git config file:

[difftool "meld"]
cmd = "C:/Program Files (x86)/Meld/Meld.exe" "LOCAL\" \"REMOTE" --label "DIFF (ORIGINAL MY)"
prompt = false
path = C:\Program Files (x86)\Meld\Meld.exe

Meld can be installed using Chocolatey like this from the COMMAND LINE:

choco install meld

Let's define a shell function to help us compare two sha-s (commits) under [alias] in the TEXT EDITOR:

showchangesbetween = "!w() { git difftool \"$1\" \"$2\" --dir-diff --ignore-all-space; }; w"

To compare the commits with the help of Meld (or your other favorite diff tool, just type at the COMMAND LINE:

git showchangesbetween somesha123 somesha456

The commit sha-s are easily visible typing

 git log 

for example.

Make git automatically remove trailing whitespace before committing

I found a git pre-commit hook that removes trailing whitespace.


if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   # Initial commit: diff against an empty tree object
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
   # Fix them!
   sed -i 's/[[:space:]]*$//' "$FILE"
   git add "$FILE"

Accessing localhost (xampp) from another computer over LAN network - how to?

First you go to Command Prompt and type

Notepad C:/windows/system32/drivers/etc/hosts

then add your ip adress below then the url of your site.

Second you go to Command Prompt and type notepad c:/xampp/bin/apache/apache2.4.18/conf/extra/httpd-vhosts.conf

then add this below

documentroot "Directory of your site"
Allow from all
Require all granted

Can't ping a local VM from the host

Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: